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

后端 未结 4 648
不知归路
不知归路 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:18

    Here's one attempt at justification for the lack of warning or error that I just came up with, and I haven't even been drinking!

    Abstract your code further, what is the intention?

    ICanEat beast = SomeFactory.CreateRavenousBeast();
    beast.Eat("sheep");
    

    You are feeding something. How the beast actually eats it up to the beast. If it was given soup, it might decide to use a spoon. It might use a knife and fork to eat the sheep. It might rip it to shreds with its teeth. But the point is as a caller of this class we don't care how it eats, we just want it to be fed.

    Ultimately it is up to the beast to decide how to eat what it is given. If the beast decides it can eat an ICloneable and an IConvertible then it's up to the beast to figure out how to handle both cases. Why should the gamekeeper care how the animals eat their meals?

    If it did cause a compile-time error you make implementing a new interface being a breaking change. For example, if you ship HungryWolf as ICanEat and then months later add ICanEat you break every place where it was used with a type that implements both interfaces.

    And it cuts both ways. If the generic argument only implements ICloneable it would work quite happily with the wolf. Tests pass, ship that, thank you very much Mr. Wolf. Next year you add IConvertible support to your type and BANG! Not that helpful an error, really.

提交回复
热议问题