C# variance problem: Assigning List as List<Base>

前端 未结 5 838
醉酒成梦
醉酒成梦 2020-11-21 06:34

Look at the following example (partially taken from MSDN Blog):

class Animal { }
class Giraffe : Animal { }

static void Main(string[] args)
{
    // Array a         


        
5条回答
  •  梦谈多话
    2020-11-21 07:25

    Covariance/contravariance can't be supported on mutable collections as others have mentioned because it's impossible to guarantee type safety both ways at compile time; however, it is possible to do a quick one-way conversion in C# 3.5, if that is what you're looking for:

    List giraffes = new List();
    List animals = giraffes.Cast().ToList();
    

    Of course it's not the same thing, it's not actually covariance - you're actually creating another list, but it is a "workaround" so to speak.

    In .NET 2.0, you can take advantage of array covariance to simplify the code:

    List giraffes = new List();
    List animals = new List(giraffes.ToArray());
    

    But be aware that you're actually creating two new collections here.

提交回复
热议问题