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

前端 未结 7 855
醉梦人生
醉梦人生 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:44

    Bala's answer is correct, but it might be helpful to see why you'd want to do this. Consider the problem that the BCL designers were faced with when designing the libraries for CLR version 2. There was an existing interface:

    interface IEnumerable
    {
      IEnumerator GetEnumerator();
    }
    

    Now you want to add:

    interface IEnumerable : IEnumerable
    {
      new IEnumerator GetEnumerator();
    }
    

    The new interface differs from the old solely in the return type.

    What are your choices?

    1) Mark the new GetEnumerator as "new" so that the compiler knows that this is intended to be the new method that does not conflict with the old method of the same name but different return type.

    2) Change the name to GetEnumerator2.

    3) Don't inherit from the original IEnumerable.

    Options 2 and 3 are awful. Option 1 is awesome: new enumerables work seamlessly with code that expects old enumerables, but code written to use the new enumerables get the "new" generic behaviour by default.

提交回复
热议问题