用字符串初始化委托

时间:2016-10-20 10:09:14

标签: c# .net delegates

有没有办法用字符串初始化委托?即你不知道需要在运行时调用的函数的名称?或者我猜有更好的办法吗?

   delegate void TestDelegate(myClass obj);

   void TestFunction()
   {
        TestDelegate td = new TestDelegate(myFuncName);  // works
        TestDelegate td = new TestDelegate("myFuncName");  // doesn't work
   }

更新

我目前拥有的代码是否无效

 class Program
{
    static void Main(string[] args)
    {
        Bish b = new Bish();
        b.MMM();

        Console.Read();
    }
}

class Bish
{
    delegate void TestDelegate();
    public void MMM()
    {
        TestDelegate tDel = (TestDelegate)this.GetType().GetMethod("PrintMe").CreateDelegate(typeof(TestDelegate));
        tDel.Invoke();
    }

    void PrintMe()
    {
        Console.WriteLine("blah");
    }
}

1 个答案:

答案 0 :(得分:2)

您可以通过这种方式创建动态委托

class Bish
{
    delegate void TestDelegate();
    delegate void TestDelegateWithParams(string parm);

    public void MMM()
    {
        TestDelegate tDel = () => { this.GetType().GetMethod("PrintMe").Invoke(this, null); };
        tDel.Invoke();

        TestDelegateWithParams tDel2 = (param) => { this.GetType().GetMethod("PrintMeWithParams").Invoke(this, new object[] { param }); };
        tDel2.Invoke("Test");
    }

    public void PrintMe()
    {
        Console.WriteLine("blah");
    }

    public void PrintMeWithParams(string param)
    {
        Console.WriteLine(param);
    }
}