Why can't I compile a custom event declared in a class interface in C #

Say I have this:

public interface ISlider { event CustomEventDelegate CustomEvent; 

In the class where I implement ISlider, I tried this

 public CustomEventDelegate CustomEvent = delegate { }; 

But he says CustomEvent is not implemented.

I need to do something like this:

  ISlider ISlider; ISlider = slider as ISlider; if (ISlider != null) { ISlider.CustomEvent += new CustomEventDelegate(MyCustomEventHandler); } else { // standard control this.slider.ValueChanged += new RoutedPropertyChangedEventHandler<double>(this.slider_ValueChange); } 
+4
source share
1 answer

Itโ€™s just a field, not an event.

The event is actually a couple of methods (for example, how the property works), but a field like events makes it trivial (you can even specify a default value other than zero, which (I assume) is your intention:

 public event CustomEventDelegate CustomEvent = delegate { }; ^^^^^ <==== note the addition of "event" here 

It looks like this:

 private CustomEventDelegate customEvent = delegate { }; public event CustomEventDelegate CustomEvent { add { customEvent += value;} remove { customEvent -= value;} } 

I say โ€œalmostโ€ because field events also include some thread safety code, which is rarely necessary but difficult to explain (and depends on which version of the compiler you are using).

Of course, in my opinion, itโ€™s better not to use this at all and just check the event for null:

 var snapshot = EventOrFieldName; if(snapshot != null) snapshot(args); 

An example implementation of this interface:

 public interface ISlider { event CustomEventDelegate CustomEvent; } public class MyType : ISlider { public event CustomEventDelegate CustomEvent = delegate { }; } 
+6
source

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


All Articles