Explicit interface implementation cannot be virtual

后端 未结 5 1729
遥遥无期
遥遥无期 2021-02-05 13:20

For the record, I\'ve already seen this connect item but I can\'t really understand what would be the problem in supporting this.

Say I have the following code:

5条回答
  •  北海茫月
    2021-02-05 13:49

    I think the reason can be simply shown in following example. Consider this code:

    public interface IInterfaceA
    {
        void Method();
    }
    
    public interface IInterfaceB
    {
        void Method();
    }
    
    public class Base : IInterfaceA, IInterfaceB
    {
        virtual void IInterfaceA.Method()
        {
           ...
        }
    
        virtual void IInterfaceB.Method()
        {
           ...
        }
    }
    
    public class Derived : Base
    {
        public override void Method()
        {
            // Will this override IInterfaceA or IInterfaceB implementation???
        }
    }
    

    So, in short, if you explicitly implement multiple interfaces with the same method signature your derived classes will not know which base method you want to override.

提交回复
热议问题