What does 'new' keyword mean when used inside an interface in C#?

前端 未结 7 867
醉梦人生
醉梦人生 2020-12-08 10:14

Developing an interface generic I wished to declare a constructor in an interface but it says constructors are forbidden there. I\'ve tried to declare a static factory metho

7条回答
  •  臣服心动
    2020-12-08 10:32

    First, the only thing the 'new' keyword actually does is prompt the compiler to NOT produce a warning that you should use the 'new' keyword. Apart from getting rid of the warning, the keyword itself does nothing (in the context in question).

    Now, the compiler WANTS you to use the 'new' keyword when you redefine a member (property or method) already defined in an interface you inherit from, and there are at least two possible reasons for doing this. First, as Eric Lippert mentioned above, you may want a method to return a different type (or define a property of the same name with a different type). Another possibility is if you want to define different implementations for the two interfaces:

    interface A
    {
        void a();
    }
    
    interface B : A
    {
        new void a();
    }
    
    class C : B
    {
        void A.a() { Console.WriteLine("Called by interface A!"); }
        void B.a() { Console.WriteLine("Called by interface B!"); }
    }
    
    static class Test
    {
        public static void DoTest()
        {
            B b = new C();
            b.a();       // Produces "Called by interface B!"
            ((A)b).a();  // Produces "Called by interface A!"
        }
    }
    

    If you try to define B.a() in C without redefining a() in B, you get a warning that it is not a member of interface: explicit interface declaration requires that you use an interface for which the member is explicitly defined.

提交回复
热议问题