简体   繁体   中英

Any workarounds for structs failing to cast to object when the struct is the covariant type of a generic object being being casted in C#?

Say I instantiate a generic class with a covariant type parameter which is a struct , then I cast the newly created object as itself with a type parameter of object in the place of struct , the cast will fail though the variance should allow for it.

Example:

public class Succeeds {}
public struct Fails {}

var castSucceeds = (IEnumerable<object>)Enumerable.Empty<Succeeds>();
var castFails = (IEnumerable<object>)Enumerable.Empty<Fails>();

As you can see from the above this cast works thanks to the generic type of IEnumberable<T> being covariant, but when attempted with a struct instead of a class it fails. I suspect the failure is related to the need for boxing when casting a struct to an object.

Is there any way around this or am I perhaps looking at it wrong?

According to Microsoft :

Variance applies only to reference types; if you specify a value type for a variant type parameter, that type parameter is invariant for the resulting constructed type.

Try doing a manual cast:

var castFails = Enumerable.Empty<Fails>().Cast<object>();

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