私はphpであなたが次のような呼び出しを行うことができることを知っています:
$function_name = 'hello';
$function_name();
function hello() { echo 'hello'; }
これは.Netで可能ですか?
私はphpであなたが次のような呼び出しを行うことができることを知っています:
$function_name = 'hello';
$function_name();
function hello() { echo 'hello'; }
これは.Netで可能ですか?
はい。反射を使用できます。このようなもの:
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
上記のコードでは、呼び出されるメソッドには access modifier が必要public
です。非パブリック メソッドを呼び出す場合は、次のようなBindingFlags
パラメーターを使用する必要がありBindingFlags.NonPublic | BindingFlags.Instance
ます。
Type thisType = this.GetType();
MethodInfo theMethod = thisType
.GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance);
theMethod.Invoke(this, userParameters);
リフレクションを使用してクラス インスタンスのメソッドを呼び出し、動的メソッド呼び出しを行うことができます。
実際のインスタンス (this) に hello というメソッドがあるとします。
string methodName = "hello";
//Get the method information using the method info class
MethodInfo mi = this.GetType().GetMethod(methodName);
//Invoke the method
// (null- no parameter for the method call
// or you can pass the array of parameters...)
mi.Invoke(this, null);
class Program
{
static void Main(string[] args)
{
Type type = typeof(MyReflectionClass);
MethodInfo method = type.GetMethod("MyMethod");
MyReflectionClass c = new MyReflectionClass();
string result = (string)method.Invoke(c, null);
Console.WriteLine(result);
}
}
public class MyReflectionClass
{
public string MyMethod()
{
return DateTime.Now.ToString();
}
}
class Program
{
static void Main(string[] args)
{
string method = args[0]; // get name method
CallMethod(method);
}
public static void CallMethod(string method)
{
try
{
Type type = typeof(Program);
MethodInfo methodInfo = type.GetMethod(method);
methodInfo.Invoke(method, null);
}
catch(Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
Console.ReadKey();
}
}
public static void Hello()
{
string a = "hello world!";
Console.WriteLine(a);
Console.ReadKey();
}
}
ちょっとした接線 -- (ネストされた!) 関数を含む式文字列全体を解析して評価する場合は、NCalc ( http://ncalc.codeplex.com/および nuget) を検討してください。
元。プロジェクトのドキュメントからわずかに変更されました:
// the expression to evaluate, e.g. from user input (like a calculator program, hint hint college students)
var exprStr = "10 + MyFunction(3, 6)";
Expression e = new Expression(exprString);
// tell it how to handle your custom function
e.EvaluateFunction += delegate(string name, FunctionArgs args) {
if (name == "MyFunction")
args.Result = (int)args.Parameters[0].Evaluate() + (int)args.Parameters[1].Evaluate();
};
// confirm it worked
Debug.Assert(19 == e.Evaluate());
そして、EvaluateFunction
デリゲート内で既存の関数を呼び出します。