简体   繁体   English

类型转换为EntityCollection <Object>

[英]Type casting to EntityCollection<Object>

I have a method taking a parameter EntityCollection 我有一个采用参数EntityCollection的方法

Say: 说:

DisplayItems(EntityCollection<Object> items);

Why is it not possible to call? 为什么不能打电话?

EntityCollection<Student> students;

DisplayItems((EntityCollection<Object>) students); //type casting here

How can I achieve this? 我该如何实现?

Please help 请帮忙

Your problem occurs because of Covariance and Contravariance , imagine that worked as you want it to, you could then do this : 您的问题是由于协方差和协方差而发生的 ,想象一下按您希望的那样工作,然后可以这样做:

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 

Clearly adding instances that are not of type Student to the EntityCollection<Student> causes a massive problem which is one of the reasons this is not allowed, you can alter this behaviour for interfaces using the In and Out keywords. 显然,将非Student类型的实例添加到EntityCollection<Student>会导致一个严重的问题,这是不允许这样做的原因之一,您可以使用InOut关键字更改接口的此行为。

Similar answer can be found here: 在这里可以找到类似的答案:

convert or cast a List<t> to EntityCollection<T> 将List <t>转换或转换为EntityCollection <T>

You need to loop and cast each element individually, adding them to a new EntityCollection. 您需要循环循环并强制转换每个元素,然后将它们添加到新的EntityCollection中。

Another option would be to use the Cast() method, but I'm not sure that will work with an EntityCollection. 另一个选择是使用Cast()方法,但是我不确定这是否可以与EntityCollection一起使用。 It works with a List: 它适用于列表:

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

I'm unable to check this would work with an EntityCollection but worth a try? 我无法检查这是否可以使用EntityCollection,但值得一试吗?

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

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