0

How to add a method to delegate Using reflection? Let us consider im having two assemblies,one AAA contains the definition of delegates and another one BBB contains the method to be added to the delegate.In BBB i have add the method to the delegate in AAA.How to accomplish this scenario?

Greg
  • 21,235
  • 17
  • 84
  • 107
user518333
  • 45
  • 3
  • 2
    What do you mean with "add the method to the delegate"? Can you perhaps show a small code sample of what you try to achieve (pseudo-code is fine, just to communicate the idea). Also, check if this covers your needs: http://stackoverflow.com/questions/3024253/create-delegate-via-reflection – Fredrik Mörk Nov 29 '10 at 09:51
  • Actually i had event and delegate declaration in BBB, and a handler method in AAA. i Successfully Subscribed a method to an event in AAA. Now i have to implement the without using event ie have to add a method of AAA to a delegate of BBB in AAA Coding Segment – user518333 Nov 29 '10 at 10:10

1 Answers1

3

Something like this (warning - not compile tested):

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

If it's not an event you want to add to, but just another Delegate, then you use Delegate.Combine:

Delegate combinedDelegate = Delegate.Combine(oldDelegate, methodDelegate);
thecoop
  • 45,220
  • 19
  • 132
  • 189