2010-11-29 47 views
0

如何添加委托方法使用反射?让我们考虑有两个程序集,一个AAA包含委托的定义,另一个包含要添加到委托的方法。在BBB中,我已将方法添加到AAA中的委托。如何完成此方案?C#中的代表

+2

什么你的意思是“将方法添加到委托”?你也许可以展示一个你试图实现的小代码示例(伪代码很好,只是为了传达这个想法)。此外,请检查这是否涵盖您的需求:http://stackoverflow.com/questions/3024253/create-delegate-via-reflection – 2010-11-29 09:51:48

回答

3

像这样的东西(警告 - 不编译测试):

// get the methodinfo for the method you want to add 
MethodInfo methodToAdd = typeof(AAA).GetMethod("MyMethod"); 

// create a delegate instance for it 
Delegate methodDelegate = Delegate.CreateDelegate(typeof(BBB.MyDelegate), methodToAdd); 

// get the event you want to add to 
EventInfo eventToAddMethodTo = typeof(BBB).GetEvent("MyEvent"); 

// call the event's add method, with the delegate you want to add 
eventToAddMethodTo.AddEventHandler(null /*or the AAA instance if this is a non-static event */, methodDelegate); 

如果这不是你想要添加到一个事件,但只是一个Delegate,那么你用Delegate.Combine

Delegate combinedDelegate = Delegate.Combine(oldDelegate, methodDelegate);