Is it possible to create an event on the object, outside it, without a special function

public class a
{
   public event eventhandler test;
   public void  RaiseTest(){//fire test}
}

Is it possible to raise the test for this class outside the class without calling the method?

Basically, I have a large number of events that should be raised based on an external source and do not want to create the Raise () function for each of them.

Is it possible to create a generic Raise () that accepts an event that should be raised as a parameter? so will it still be called from within the class?

+3
source share
2 answers

Reflection, . #, + "". GetValue , MulticastDelegate.

MulticastDelegate, :

EventArgs e = new EventArgs(myClassInstance);  // Create appropriate EventArgs

MulticastDelegate eventDelagate = 
    this.GetType().GetField(theEventName + "Event",
    System.Reflection.BindingFlags.Instance | 
    System.Reflection.BindingFlags.NonPublic).GetValue(myClassInstance) as MulticastDelegate;

Delegate[] delegates = eventDelagate.GetInvocationList();
foreach (Delegate del in delegates) {  
      del.Method.Invoke(del.Target, new object[] { myClassInstance, e }); 
}

, NonPublic , .

Raise(), , ? ?

. . "myClassInstance" . , NonPublic BindingFlag .

+4

, ?

: .

, ,

Raise(), , ? ?

, , , ... , EventInfo.Invoke. AFAIK,

EDIT: (. Reed answer), , .

+2

Source: https://habr.com/ru/post/1714348/


All Articles