Why doesn't C# do “simple” type inference on generics?

后端 未结 6 1341
谎友^
谎友^ 2021-01-03 05:45

Just curious: sure, we all know that the general case of type inference for generics is undecidable. And so C# won\'t do any kind of sub-typing at all: if Foo

6条回答
  •  星月不相逢
    2021-01-03 06:16

    They already have solved it for many of the "easy" cases: C# 4.0 supports covariance and contravariance for generic type parameters in interfaces and delegates. But not classes unfortunately.

    It's fairly easy to workaround this limitation:

    List foos = bars.Select(bar => (Foo)bar).ToList();
    

提交回复
热议问题