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

前端 未结 5 1958
爱一瞬间的悲伤
爱一瞬间的悲伤 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:12

    Back in 2009 Eric teased us that things would change in C# 4. So where do we stand today?

    The classes used in my answer can be found at the bottom. To make this easier to follow, we will use a Mammal class as "parent", and Cat and Dog classes as "children". Cats and dogs are both mammals, but a cat is not a dog and a dog is not a cat.

    This still isn't legal, and can't be:

    List cats = new List();
    
    List mammals = cats;
    

    Why not? Cats are mammals, so why can't we assign a list of cats to a List?

    Because, if we were allowed to store a reference to a List in a List variable we would then be able to compile the following code to add a dog to a list of cats:

    mammals.Add(new Dog());
    

    We mustn't allow that! Remember, mammals is just a reference to cats. Dog does not descend from Cat and has no business being in a list of Cat objects.

    Starting with .NET Framework 4, several generic interfaces have covariant type parameters declared with the out Generic Modifier keyword introduced in C# 4. Amongst these interfaces is IEnumerable which of course is implemented by List.

    That means we can now cast a List to an IEnumerable:

    IEnumerable mammalsEnumerable = cats;
    

    We can't add a new Dog to mammalsEnumerable because IEnumerable is a "read-only" interface i.e. it has no Add() method, but we can now use cats wherever a IEnumerable can be consumed. For example, we can concatenate mammalsEnumerable with a List to return a new sequence:

    void Main()
    {
        List cats = new List { new Cat() };
        IEnumerable mammalsEnumerable =
            AddDogs(cats); // AddDogs() takes an IEnumerable
        Console.WriteLine(mammalsEnumerable.Count()); // Output: 3. One cat, two dogs.
    }
    
    public IEnumerable AddDogs(IEnumerable parentSequence)
    {
        List dogs = new List { new Dog(), new Dog() };
        return parentSequence.Concat(dogs);
    }
    

    Class definitions:

    public abstract class Mammal { }
    
    public class Cat: Mammal { }
    
    public class Dog : Mammal { }
    

提交回复
热议问题