如何将方法名称传递给另一个方法并通过委托变量调用它?

我有一个方法,包含指向另一个类的委托变量。 我想通过此委托调用该类中的方法,但将方法的名称作为字符串传递给包含委托的方法。

如何才能做到这一点? 用reflection? Func

编辑:

我现在明白,反思可能不是最好的解决方案。

这就是我所拥有的:

 private static void MethodContainingDelegate(string methodNameInOtherClassAsString) { _listOfSub.ForEach(delegate(Callback callback) { //Here the first works, but I want the method to be general and // therefore pass the method name as a string, not specfify it. callback.MethodNameInOtherClass(); //This below is what I am trying to get to work. callback.MethodNameInOtherClassAsString(); } }); } 

所以,基本上,我正在寻找一种方法让我的回调委托“认识到”我的methodNameInOtherClassAsString实际上是一个在另一个类中执行的方法。

谢谢!

这很简单:

 public delegate void DelegateTypeWithParam(object param); public delegate void DelegateTypeWithoutParam(); public void MethodWithCallbackParam(DelegateTypeWithParam callback, DelegateTypeWithoutParam callback2) { callback(new object()); Console.WriteLine(callback.Method.Name); callback2(); Console.WriteLine(callback2.Method.Name); } // must conform to the delegate spec public void MethodWithParam(object param) { } public void MethodWithoutParam() { } public void PassCallback() { MethodWithCallbackParam(MethodWithParam, MethodWithoutParam); } 

无关紧要,委托变量指向哪个类。 它可以在另一个类中定义 – 没有太大区别。

我想你甚至可以从委托变量本身查询原始方法的名称而不用reflection。 每个委托都有一个名为Method的属性。

你可以这样做:

 var mi = typeof(Foo).GetMethods().Single(x => x.Name == "Bar"); mi.Invoke(foo, null); 

如果Foo是您的目标类,Bar就是您要调用的方法。 但是你应该注意到reflection会对你的程序性能产生很大的影响。 请考虑使用强类型代理。

假设您有方法名称的字符串表示forms:

 var methodInfo = myObject.GetType().GetMethod(myString); //<- this can throw or return null methodInfo.Invoke(myObject, new object[n]{parm1, pram2,...paramn}); 

你需要为此添加一些错误检查,如果可以,应该使用更具体的GetMethod版本。