[英]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
,它违反了类型规则,因为Manager
和Associate
没有类关系。 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: 以下是避免此问题的可能方法:
var
in code to implicitly define type of variable (it indeed will be of type List<Associate>
var
来隐式定义变量的类型(它确实是List<Associate>
类型 IEnumerable<Employee>
(and you'll be able to pass either List<Employee>
or List<Associate>
) IEnumerable<Employee>
(你将能够传递List<Employee>
或List<Associate>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.