How do I cast a List effectively?

前端 未结 8 1415
暖寄归人
暖寄归人 2020-12-08 15:09

I have a

List 

but I need a

List  

Is there a way to cast this in c

8条回答
  •  悲哀的现实
    2020-12-08 15:36

    ConvertAll seems like a better solution, since it doesn't depend on Linq library and is shorter and more intuitive.

    But both of them are rather workarounds, than solutions. Both of them create a new collection with the same data. There should be a support for generic covariance in .net, i.e. upcasting in the generic collections, which would allow you to do that naturally. For example:

    List ls = (List)List
    

    From my search so far, my conclusion, is that .Net as of 3.5 doesn't support this feature. Hence we have to end up with workarounds.

    These are the discussions on the topic:

    • C# generic Covariance
    • Covariant Generic List
    • Are Generics Covariant, Contra-Variant, or Invariant?

提交回复
热议问题