简体   繁体   English

如何在C#中将派生类型列表分配给基类型列表?

[英]How to assign a derived type list to base type list in C#?

How to achieve List<Employee> e = new List<Associate>() ? 如何实现List<Employee> e = new List<Associate>() Is this wrong? 这是错的吗?

class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
}

class Associate : Employee
{
}

class Compute
{
    static void Main()
    {
        List<Employee> e = new List<Associate>();
    }
}

Imagine you have another class that inherits from Employee as well, say, 想象一下,你有另一个继承自Employee类,比方说,

class Manager : Employee
{
}

Then, in your example this could happen, 然后,在你的例子中,这可能发生,

class Compute
{
    static void Main()
    {
        List<Employee> employees = new List<Associate>();
        employees.Add(new Manager()); // Hmmm... what?
    }
}

And suddenly you have a Manager in a list of Associate , which violate the type rules because Manager and Associate have no class relationship. 突然你在一个Associate列表中有一个Manager ,它违反了类型规则,因为ManagerAssociate没有类关系。 That's part of the reason why List<T> has the declared the T type parameter as invariant (rather than List<out T> or covariant, where something like this could actually happen). 这就是为什么List<T>将声明的T类型参数声明为不变的原因 (而不是List<out T>或covariant,其中这样的事情实际上可能发生)。

You can add derived classes to lists of base classes. 您可以将派生类添加到基类列表中。

List<Employee> e= new List<Employee>();
e.Add(new Associate());

You can not. 你不能。 The reason of this behavior is that you still will be able to add base class instances to a list what should be just derived classes (as covered in blogs.msdn provided by BrunoLM). 这种行为的原因是你仍然可以将基类实例添加到列表应该只是派生类(如BrunoLM提供的blogs.msdn中所述)。

e.Add(new Employee());

Following are possible ways to avoid the problem: 以下是避免此问题的可能方法:

  • you can have list of base class items as you can easily add instances of derived class. 您可以拥有基类项列表,因为您可以轻松添加派生类的实例。
  • you can use var in code to implicitly define type of variable (it indeed will be of type List<Associate> 你可以在代码中使用var来隐式定义变量的类型(它确实是List<Associate>类型
  • if you need to pass this list to a function - make argument IEnumerable<Employee> (and you'll be able to pass either List<Employee> or List<Associate> ) 如果你需要将这个列表传递给一个函数 - make参数IEnumerable<Employee> (你将能够传递List<Employee>List<Associate>
  • you can use Enumerable.OfType to filter elements of derived classes from list of elements of base class. 您可以使用Enumerable.OfType从基类元素列表中过滤派生类的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM