C# 类型转换到EntityCollection

C# 类型转换到EntityCollection,c#,C#,我有一个接受参数EntityCollection的方法 说: 为什么不能打电话 EntityCollection<Student> students; DisplayItems((EntityCollection<Object>) students); //type casting here 我怎样才能做到这一点 请帮助类似的答案可以在这里找到: 您需要单独循环和强制转换每个元素,将它们添加到新的EntityCollection 另一个选择是使用Cast方法,但我不确

我有一个接受参数EntityCollection的方法

说:

为什么不能打电话

EntityCollection<Student> students;

DisplayItems((EntityCollection<Object>) students); //type casting here
我怎样才能做到这一点


请帮助

类似的答案可以在这里找到:

您需要单独循环和强制转换每个元素,将它们添加到新的EntityCollection

另一个选择是使用Cast方法,但我不确定这是否适用于EntityCollection。它与一个列表一起工作:

List<Object> myItems = students.Cast<Object>().ToList();

我无法检查EntityCollection是否可以执行此操作,但值得一试吗?

您的问题之所以出现,是因为,假设按您希望的方式执行,您可以执行以下操作:

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会导致大量问题,这是不允许的原因之一,您可以使用In和Out关键字更改接口的此行为。

No,这与将列表转换为EntityCollection无关-这是关于EntityCollection和EntityCollection之间的抵销/合并差异。完全不同的鱼!我明白,但校长是一样的。类型化列表不能轻易地从一个元素转换到另一个元素,通常一次只能转换一个元素。
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