Why to Use Explicit Interface Implementation To Invoke a Protected Method?

后端 未结 3 729
南笙
南笙 2021-01-02 05:29

When browsing ASP.NET MVC source code in codeplex, I found it is common to have a class explicitly implementing interface. The explicitly implemented method/property then in

3条回答
  •  被撕碎了的回忆
    2021-01-02 06:02

    1. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface. reference : Explicit Interface Implementation Tutorial
    2. As my experience if interface implementer explicitly implement an interface he will receive compiler error after you drop a method from interface while he will not notify if he/she implicitly implement it and the method will remain in the code.

    sample for reason 1:

    public interface IFoo
    {
        void method1();
        void method2();
    }
    
    public class Foo : IFoo
    {
        // you can't declare explicit implemented method as public
        void IFoo.method1() 
        {
        }
    
        public void method2()
        {
        }
    
        private void test()
        {
            var foo = new Foo();
            foo.method1(); //ERROR: not accessible because foo is object instance
            method1(); //ERROR: not accessible because foo is object instance
            foo.method2(); //OK
            method2(); //OK
    
            IFoo ifoo = new Foo();
            ifoo.method1(); //OK, because ifoo declared as interface
            ifoo.method2(); //OK
        }
    }
    

提交回复
热议问题