如何传递方法名称另一种方法,并通过一个委托变量调用它呢? [英] How can I pass a method name to another method and call it via a delegate variable?

查看:417
本文介绍了如何传递方法名称另一种方法,并通过一个委托变量调用它呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含指向另一个类的委托变量的方法。 我想通过这个委托来调用这个类的方法,但通过该方法的名字作为一个字符串包含委托的方法。

I have a method that contains a delegate variable that points at another class. I want to call a method in that class via this delegate, but pass the name of the method as a string to the method containing the delegate.

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

How can this be done? Using reflection? Func<T>?

编辑:

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

I understand now that reflection may not be the best solution.

这是我有:

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实际上是在其他类来执行的方法。

So, basically, I am looking for a way to make my callback delegate "recognize" that my methodNameInOtherClassAsString is actually a method to execute in the other class.

谢谢!

推荐答案

这是非常简单的:

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

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

It doesn't matter, what class does the delegate variable point to. It can be defined in another class -- there's not much difference.

我觉得你甚至可以查询从委托变量本身没有反映原始方法的名称。每个代表都有方法称为属性正是为了这一点。

I think you could even query the name of the original method from the delegate variable itself without reflection. Every delegate has a property called Method exactly for that.

这篇关于如何传递方法名称另一种方法,并通过一个委托变量调用它呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆