简体   繁体   English

C# 铸造通用 class 接口作为占位符

[英]C# casting generic class with an interface as placeholder

I have the following classes/interfaces:我有以下类/接口:

public interface IConvexPolygon<T> where T : IPositionable
{
    IEnumerable<FPVector2> UniqueAxes { get; }
    IEnumerable<T> CornerPositionsClockwise { get; }
}
public class ConvexPolygon<T> : ConvexShape, IConvexPolygon<T> where T : IPositionable
{
...
}
public struct Positionable : IPositionable
{
...
}

I now want to cast a ConvexPolygon<Positionable> to IConvexPolygon<IPositionable> to be able to use its getters.我现在想将一个ConvexPolygon<Positionable>转换为IConvexPolygon<IPositionable>以便能够使用它的吸气剂。 This throws an invalid cast exception.这会引发无效的强制转换异常。 I tried specifying covariance with out in the IConvexPolygon interface, with the same result我尝试在 IConvexPolygon 接口中使用out指定协方差,结果相同

Variance is applied only to references types, see the docs :方差仅适用于引用类型,请参阅文档

  • 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.如果为变体类型参数指定值类型,则该类型参数对于生成的构造类型是不变的。

So you will need to change Positionable from struct to class, to make this cast work.因此,您需要将Positionable从 struct 更改为 class,以使此演员表工作。

Also if you are planning to work Positionable via interface take in account that it will be boxed .此外,如果您打算通过接口使用Positionable ,请考虑它将被装箱

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

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