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

前端 未结 5 820
醉酒成梦
醉酒成梦 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:27

    In terms of List, I'm afraid you're out of luck. However, .NET 4.0/C# 4.0 adds support for covariant/contravariant interfaces. Specifically, IEnumerable is now defined as IEnumerable, which means that the type parameter is now covariant.

    This means you can do something like this in C# 4.0...

    // implicit casting
    IEnumerable animalsList = new List();
    
    // explicit casting
    IEnumerable animalsList2 = (IEnumerable) new List();
    

    Note: Array types have also been covariant (at least since .NET 1.1).

    I think it's a shame that variance support wasn't added for IList and other similar generic interfaces (or generic classes even), but oh well, at least we have something.

提交回复
热议问题