2016-10-20 82 views
1

是否有任何方式使用字符串初始化委托?即你不会知道需要在运行时调用的函数的名字吗?或者我猜这样做有更好的方法吗?使用字符串初始化委托使用字符串

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

回答

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

我得到一个系统空引用异常? – mHelpMe

+0

@mHelpMe方法是静态的吗? – IllidanS4

+0

@ IllidanS4我刚刚在 – mHelpMe