Why C# doesn't allow inheritance of return type when implementing an Interface

后端 未结 6 676
一生所求
一生所求 2020-11-28 14:24

Is there any rational reason why the code below is not legal in C#?

class X: IA, IB
{
    public X test() // Compliation Error, saying that X is not IB
    {         


        
6条回答
  •  温柔的废话
    2020-11-28 14:48

    The signatures must match exactly to what the interface specifies. There's no reason you cannot return an instance of X from the method, but the method signature will have to use IB.

    As for a rational reason.. it's probably preferable from a code readability point of view.

    You could implement the interface explicitly, and provide an alternative signature that returns X that is not defined by the interface. If you know your IA is actually an X, you could use that instead.

提交回复
热议问题