How do I cast a List effectively?

前端 未结 8 1414
暖寄归人
暖寄归人 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:35

    Just in case: I've little C# experience, but if this generic construction means the same thing it does in Java, then you must create a whole new List parametrized by the supertype. In other words, if every instance of Bangle is also an instance of Akthud, it does not follow that every List is also a List.

    The reason for this is that you can have two references to this List. If the second reference casts and then refers to it as a List, then it is permitted to add an Akthud to it - but now the first reference has a List whose members are not all Bangles. Violation!

    That being said, David B's answer should indeed do what you want, correctly, AFAICT. (It looks like a copy operation.)

    [And if I'm misunderstanding the semantics of C# generics, I hope someone corrects me in a comment!]

提交回复
热议问题