C# 使用接口作为占位符转换泛型 class

C# casting generic class with an interface as placeholder

我有以下 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
{
...
}

我现在想将 ConvexPolygon<Positionable> 转换为 IConvexPolygon<IPositionable> 以便能够使用它的 getter。这会抛出一个无效的转换异常。我尝试在 IConvexPolygon 接口中使用 out 指定协方差,结果相同

变体仅适用于引用类型,请参阅 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.

因此您需要将 Positionable 从结构更改为 class,以使此转换工作。

此外,如果您打算通过界面工作 Positionable,请考虑 will be boxed