我有一个接受参数EntityCollection的方法
可以这样说:
DisplayItems(EntityCollection<Object> items);为什么不能打电话?
EntityCollection<Student> students;
DisplayItems((EntityCollection<Object>) students); //type casting here我如何才能做到这一点?
请帮帮忙
发布于 2011-04-08 18:40:17
你的问题是因为Covariance and Contravariance而发生的,想象一下你想要的那样工作,然后你可以这样做:
public void DisplayItems(EntityCollection<Object> items)
{
//Probably not called add but you get the idea...
items.Add(new AnyObjectILike());
items.Add(new System.Windows.Form());
}
EntityCollection<Student> students;
DisplayItems((EntityCollection<Object>) students); //type casting here 显然,将非Student类型的实例添加到EntityCollection<Student>会导致大量问题,这也是不允许这样做的原因之一,您可以使用In和Out关键字来更改接口的此行为。
发布于 2011-04-08 18:32:58
类似的答案可以在这里找到:
convert or cast a List to EntityCollection
您需要分别循环和强制转换每个元素,将它们添加到新的EntityCollection中。
另一种选择是使用Cast()方法,但我不确定这是否适用于EntityCollection。它使用一个列表:
List<Object> myItems = students.Cast<Object>().ToList();我无法检查这是否可以与EntityCollection一起工作,但值得一试吗?
https://stackoverflow.com/questions/5593738
复制相似问题