簡體   English   中英

C# 鑄造通用 class 接口作為占位符

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

我有以下類/接口:

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>以便能夠使用它的吸氣劑。 這會引發無效的強制轉換異常。 我嘗試在 IConvexPolygon 接口中使用out指定協方差,結果相同

方差僅適用於引用類型,請參閱文檔

  • 差異僅適用於引用類型; 如果為變體類型參數指定值類型,則該類型參數對於生成的構造類型是不變的。

因此,您需要將Positionable從 struct 更改為 class,以使此演員表工作。

此外,如果您打算通過接口使用Positionable ,請考慮它將被裝箱

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM