Java到C#:在Generic中扩展

问题描述 投票:3回答:3

我试图将这个Java(Android)代码转换为c#(MonoDroid),但我不明白<Item extends OverlayItem>

public class BalloonOverlayView<Item extends OverlayItem> extends FrameLayout
c# java android xamarin.android
3个回答
9
投票

它正在为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.


3
投票

它与此相同:

public class BalloonOverlayView<Item> : FrameLayout where Item : OverlayItem

1
投票

这意味着参数化类型Item必须是OverlayItem的子类

从语义上讲,这意味着如果不扩展OverlayItem,使用参数化类型实例化BalloonOverlayView是没有意义的。

© www.soinside.com 2019 - 2024. All rights reserved.