Why I cannot compile a Custom Event declared in a Class Interface in C#

前端 未结 1 611
我在风中等你
我在风中等你 2021-01-13 18:58

Let\'s say I have this:

public interface ISlider {
    event CustomEventDelegate CustomEvent;

In the class where I implements ISlider, I tr

相关标签:
1条回答
  • 2021-01-13 19:36

    Simply - that is a field, not an event.

    An event is actually a pair of methods (like how a property works) - but field like events make that trivial (you can even include your default non-null value, which is (I assume) your intent:

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

    That translates almost like:

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

    I say "almost" because field-like events also include some thread-safety code, which is rarely needed but tricky to explain (and varies depending on which version of the compiler you are using).

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

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

    Example of implementing this interface:

    public interface ISlider
    {
        event CustomEventDelegate CustomEvent;
    }
    public class MyType : ISlider
    {
        public event CustomEventDelegate CustomEvent = delegate { };
    }
    
    0 讨论(0)
提交回复
热议问题