2010-07-12 55 views
3

当通过反射动态地将方法分配给委托实例时,我陷入困境。以下是我面对的情况的一个示例场景。通过反射分配方法进行委托

class Program 
{ 
    static void Main(string[] args) 
    { 
     new DynamicDelegateTest().Test();    
    } 
} 

public class DynamicDelegateTest 
{ 
    public void Test() 
    { 
     //This is what i target to do through reflection 
     ABC objABC1 = new ABC(); 
     objABC1.Proc = Debugger; 
     objABC1.Test("Helloz"); 

     //Implementing the same code through reflection 
     ABC objABC = new ABC(); 
     MethodInfo MIDebugger = GetType().GetMethod("Debugger", BindingFlags.NonPublic | BindingFlags.Instance); 
     FieldInfo MyProc = objABC.GetType().GetField("Proc", BindingFlags.Public | BindingFlags.Instance); 

     //This is the point where I got stuck up 
     MyProc.SetValue(objABC, MIDebugger); 
     objABC.Test("QWERTY"); 
    } 

    void Debugger(object Tests) 
    { 
     Console.WriteLine(Tests); 
    } 
} 

public class ABC 
{ 
    public delegate void Delg(object P1); 
    public Delg Proc; 

    public void Test(object Tst) 
    { 
     if (Proc != null) Proc(Tst); 
    } 
} 

请帮忙。

回答

10

您需要使用Delegate.CreateDelegate来获取委托实例,而不是方法信息。对于非静态方法,这也包括目标实例。在这种情况下:

object del = Delegate.CreateDelegate(MyProc.FieldType, this, MIDebugger); 
MyProc.SetValue(objABC, del);