In C#, is it possible to cast a List to List?

前端 未结 5 1952
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 05:29

I want to do something like this:

List childList = new List();
...
List parentList = childList;

How

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 06:10

    Casting directly is not allowed because there's no way to make it typesafe. If you have a list of giraffes, and you cast it to a list of animals, you could then put a tiger into a list of giraffes! The compiler wouldn't stop you, because of course a tiger may go into a list of animals. The only place the compiler can stop you is at the unsafe conversion.

    In C# 4 we'll be supporting covariance and contravariance of SAFE interfaces and delegate types that are parameterized with reference types. See here for details:

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/

提交回复
热议问题