如何动态调用c#中的函数
我有方法:
add(int x,int y)
我也有:
int a=5; int b=6; string s="add";
是否可以使用字符串s调用add(a,b)? 我怎么能在c#中做到这一点?
我怎么能在c#中做到这一点?
使用reflection。
add
必须是某种类型的成员,所以(删除了很多细节):
typeof(MyType).GetMethod("add").Invoke(null, new [] {arg1, arg2})
这假设add
是静态的(否则Invoke
第一个参数是对象),我不需要额外的参数来唯一地标识GetMethod
调用中的方法。
使用reflection – 尝试Type.GetMethod
方法
就像是
MethodInfo addMethod = this.GetType().GetMethod("add"); object result = addMethod.Invoke(this, new object[] { x, y } );
您失去了强类型和编译时检查 – 调用不知道方法期望的参数数量,它们的类型是什么以及返回值的实际类型是什么。 因此,如果你没有把它弄好的话,事情可能会在运行时失败。
它也慢了。
如果函数在编译时已知,并且您只是想避免编写switch语句。
建立:
Dictionary> functions = new Dictionary>(); functions["add"] = this.add; functions["subtract"] = this.subtract;
被称为:
string functionName = "add"; int x = 1; int y = 2; int z = functions[functionName](x, y);
你可以使用reflection。
using System; using System.Reflection; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Program p = new Program(); Type t = p.GetType(); MethodInfo mi = t.GetMethod("add", BindingFlags.NonPublic | BindingFlags.Instance); string result = mi.Invoke(p, new object[] {4, 5}).ToString(); Console.WriteLine("Result = " + result); Console.ReadLine(); } private int add(int x, int y) { return x + y; } } }
@理查德的答案很棒。 只是为了扩大它:
这在您动态创建未知类型的对象并需要调用其方法的情况下非常有用:
var do = xs.Deserialize(new XmlTextReader(ms)); // example - XML deserialization do.GetType().GetMethod("myMethodName").Invoke(do, new [] {arg1, arg2});
因为在编译时, do
只是一个Object
。