简体   繁体   中英

Casting ReadOnlyCollection<derivedType> to ReadOnlyCollection<baseType>

I was wondering if anyone could point me in the right direction...

How do I cast from ReadOnlyCollection<myDerivedType> to ReadOnlyCollection<myBaseType> without iterating or "newing up" a copy?

I am using .NET Framework 4.0

You can implicitly convert a ROC<Derived> into an IEnumerable<Base> in C# 4, but not into a ROC<Base> .

That is unfortunate; it would be really nice to be able to do covariant conversions on immutable types.

I don't believe you can, as the generic parameter T isn't defined as an out (as has been pointed out .net doesn't support Covariance and Contravariance in classes).

ReadOnlyCollection<T>

You would have to use LINQ, such as readOnlyColl.Cast<myBaseType>(); , or a loop. Internally LINQ would use a loop / iteration, making a new copy.

与Linq

yourCollection.Cast<myBaseType>();

您不能将ReadOnlyCollection<myDerivedType>ReadOnlyCollection<myBaseType>

I don't think that covariance and contravariance is allowed in C# for generic types. Generics don't support this—they're invariant .

I think that only generic delegates in C#4 has limited support for covariance and contravariance.

You can't do this, so you're probably better off passing around interfaces like IEnumerable<T> or ICollection<T> instead of concrete classes like ReadOnlyCollection<T> .

Then you can do, as others have suggested:

collection.Cast<myBaseType>();

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