我试图将这个Java(Android)代码转换为c#(MonoDroid),但我不明白<Item extends OverlayItem>
public class BalloonOverlayView<Item extends OverlayItem> extends FrameLayout
它正在为type参数添加一个约束。它类似于C#中的where
子句。
在Java中,您有:
public class BalloonOverlayView<Item extends OverlayItem> extends FrameLayout
其中Item
是必须子类化或实现类型OverlayItem
的类型参数。在C#中,这将被写为:
public class BalloonOverlayView<Item> : FrameLayout where Item : OverlayItem
您可以看到约束如何移动到最后,但在其他方面类似。它是非常common practice in C# to name type parameters prefixed with a T
,所以我会推荐名称TItem
像这样:
public class BalloonOverlayView<TItem> : FrameLayout where TItem : OverlayItem
这有助于明确类型参数和普通类型之间非常重要的区别。
有关何时需要使用类型约束的讨论,I go into this at length in a previous answer.
它与此相同:
public class BalloonOverlayView<Item> : FrameLayout where Item : OverlayItem
这意味着参数化类型Item
必须是OverlayItem
的子类
从语义上讲,这意味着如果不扩展OverlayItem
,使用参数化类型实例化BalloonOverlayView是没有意义的。