C # event inheritance

I have this program:

class One { public delegate void del(object o); public event del SomethingChanged; int x; public int X { get { return x; } set { x = value; OnSomethingChanged(this); } } protected void OnSomethingChanged(object o) { if (SomethingChanged != null) SomethingChanged(o); } } class Two: One { public void ChangeSomething() { //if (SomethingChanged != null) // SomethingChanged(this); OnSomethingChanged(this); } } static void Main(string[] args) { One one = new One(); Console.WriteLine(one.X); one.SomethingChanged += new One.del(one_SomethingChanged); one.X = 5; } static void one_SomethingChanged(object o) { Console.WriteLine(((One)o).X); } 

There are 2 classes - one and two, two - a descendant of one. An event is declared in the class One (SomethingChanged), and it is fired by the class One and class Two. But take a look at Two.ChangeSomething - it raises an event by calling the base class method. However, if I try to trigger an event using raw code, for example

  if (SomethingChanged! = null)
     SomethingChanged (this);

I get a compiler error

  The event 'One.SomethingChanged' can only appear on the left hand side of + = or - = (except when used from within the type 'eventstest.Program.One')

So I'm just curious why I can't use the raw code in class 2 to raise an event, but when I call the corresponding function event, the question arises?

[EDIT] Here were some clarifications: C #: creating an inherited event

+4
source share
4 answers

When you declare an event using the keyword "event" in C #, the generated IL actually contains two corresponding elements: a private delegate field and an access tool for events with the same visibility as the declared event. An event activator cannot be used to trigger an event. It is used only to subscribe and unsubscribe to notifications. Your code SomethingChanged(this) uses a private field to call a delegate, and this private field is not accessible outside the class.

+6
source

Code

 if (SomethingChanged != null) SomethingChanged(this); 

(by the way, has a race condition) implies calling Delegate.GetInvocationList in SomethingChanged . Automatically implemented events do not allow this if you are not in the class in which the event is defined.

You could do this if you implemented the event manually and granted protected access to the delegate field that supports the event.

+1
source

Using:

 this.SomethingChanged += new One.del(one_SomethingChanged); 
0
source

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


All Articles