【问题标题】:How can I pass a method name to another method and call it via a delegate variable?如何将方法名称传递给另一个方法并通过委托变量调用它?
【发布时间】:2011-05-20 08:55:59
【问题描述】:

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

如何做到这一点?使用反射? Func<T>?

编辑:

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

这就是我所拥有的:

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 实际上是在另一个类中执行的方法。

谢谢!

【问题讨论】:

  • 你能添加一些伪代码吗?我不太明白你在问什么!
  • 你能发布一些你的代码吗?
  • 你有什么样的参考资料?它是一个委托引用,一个带有方法名称的字符串......?

标签: c# .net methods delegates


【解决方案1】:

很简单:

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);
}

没关系,委托变量指向什么类。它可以在另一个类中定义——没有太大区别。

我认为您甚至可以从委托变量本身查询原始方法的名称而无需反射。每个委托都有一个名为 Method 的属性,正是为此。

【讨论】:

  • 感谢您的回答。我意识到也许反射不是要走的路,而是研究了 Action ,从那时起我可以将方法作为方法(动作)传递,而不必考虑从字符串转换。
【解决方案2】:

你可以这样做:

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

Foo 是您的目标类,Bar 是您要调用的方法。 但是你应该注意反射会对你的程序的性能产生很大的影响。考虑改用强类型委托。

【讨论】:

    【解决方案3】:

    假设你有方法名的字符串表示:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-10
      • 2012-12-21
      • 1970-01-01
      • 2017-07-29
      • 2012-07-21
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多