C# Language Design: explicit interface implementation of an event

后端 未结 4 606
醉话见心
醉话见心 2020-12-15 03:21

Small question about C# language design :))

If I had an interface like this:

interface IFoo {
  int Value { get; set; }
}

It\'s pos

4条回答
  •  攒了一身酷
    2020-12-15 03:50

    When explicitly implementing an event that was declared in an interface, you must use manually provide the add and remove event accessors that are typically provided by the compiler. The accessor code can connect the interface event to another event in your class or to its own delegate type.

    For example, this will trigger error CS0071:

    public delegate void MyEvent(object sender);
    
    interface ITest
    {
        event MyEvent Clicked;
    }
    
    class Test : Itest
    {
        event MyEvent ITest.Clicked;  // CS0071
        public static void Main() { }
    }
    

    The correct way would be:

    public delegate void MyEvent(object sender);
    
    interface ITest
    {
        event MyEvent Clicked;
    }
    
    class Test : Itest
    {
        private MyEvent clicked;
    
        event MyEvent Itest.Clicked
        {
            add
            {
                clicked += value;
            }
    
            remove
            {
                clicked -= value;
            }
        }
    
        public static void Main() { }
    }
    

    see Compiler Error CS0071

提交回复
热议问题