简体   繁体   中英

Type casting to EntityCollection<Object>

I have a method taking a parameter 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.

Similar answer can be found here:

convert or cast a List<t> to EntityCollection<T>

You need to loop and cast each element individually, adding them to a new EntityCollection.

Another option would be to use the Cast() method, but I'm not sure that will work with an 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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