Generic type parameter covariance and multiple interface implementations

后端 未结 5 1234
名媛妹妹
名媛妹妹 2020-12-12 22:18

If I have a generic interface with a covariant type parameter, like this:

interface IGeneric
{
    string GetName();
}

And If

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 22:53

    Holy goodness, lots of really good answers here to what is quite a tricky question. Summing up:

    • The language specification does not clearly say what to do here.
    • This scenario usually arises when someone is attempting to emulate interface covariance or contravariance; now that C# has interface variance we hope that less people will use this pattern.
    • Most of the time "just pick one" is a reasonable behaviour.
    • How the CLR actually chooses which implementation is used in an ambiguous covariant conversion is implementation-defined. Basically, it scans the metadata tables and picks the first match, and C# happens to emit the tables in source code order. You can't rely on this behaviour though; either can change without notice.

    I'd only add one other thing, and that is: the bad news is that interface reimplementation semantics do not exactly match the behaviour specified in the CLI specification in scenarios where these sorts of ambiguities arise. The good news is that the actual behaviour of the CLR when re-implementing an interface with this kind of ambiguity is generally the behaviour that you'd want. Discovering this fact led to a spirited debate between me, Anders and some of the CLI spec maintainers and the end result was no change to either the spec or the implementation. Since most C# users do not even know what interface reimplementation is to begin with, we hope that this will not adversely affect users. (No customer has ever brought it to my attention.)

提交回复
热议问题