C# Language Design: explicit interface implementation of an event

后端 未结 4 636
醉话见心
醉话见心 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:54

    I guess it might have to do with the fact that you can't call an explicit interface implementation from other members of the class:

    public interface I
    {
        void DoIt();
    }
    
    public class C : I
    {
        public C()
        {
            DoIt(); // error CS0103: The name 'DoIt' does not exist in the current context
        }
    
        void I.DoIt() { }
    }
    

    Note that you can call the method by upcasting to the interface first:((I)this).DoIt();. A bit ugly but it works.

    If events could be explicitly implemented as ControlFlow (the OP) suggested, then how would you actually raise them? Consider:

    public interface I
    {
        event EventHandler SomethingHappened;
    }
    
    public class C : I
    {
        public void OnSomethingHappened()
        {
            // Same problem as above
            SomethingHappened(this, EventArgs.Empty);
        }
    
        event EventHandler I.SomethingHappened;
    }
    

    Here you cannot even raise the event by upcasting to the interface first, because events can only be raised from within the implementing class. It therefore seems to make perfect sense to require accessor syntax for explicitly implemented events.

提交回复
热议问题