No warning or error (or runtime failure) when contravariance leads to ambiguity

后端 未结 4 646
不知归路
不知归路 2021-01-30 10:29

First, remember that a .NET String is both IConvertible and ICloneable.

Now, consider the following quite simple code:

<         


        
4条回答
  •  北海茫月
    2021-01-30 11:31

    Another explanation: there is no ambiguity, therefore there is no compiler warning.

    Bear with me.

    ICanEat wolf = new HungryWolf();
    wolf.Eat("sheep");
    

    There is no error because ICanEat only contains one method called Eat with those parameters. But say this instead and you do get an error:

    HungryWolf wolf = new HungryWolf();
    wolf.Eat("sheep");
    

    HungryWolf is ambiguous, not ICanEat. In expecting a compiler error you are asking the compiler to look at the value of the variable at the point at which Eat is called and work out if it is ambiguous, which it not necessarily something that can it can deduce. Consider a class UnambiguousCow which only implements ICanEat.

    ICanEat beast;
    
    if (somethingUnpredictable)
        beast = new HungryWolf();
    else
        beast = new UnambiguousCow();
    
    beast.Eat("dinner");
    

    Where and how would you expect a compiler error to be raised?

提交回复
热议问题