Java 到 C#:在泛型中扩展 [英] Java to C#: Extends in Generic

查看:17
本文介绍了Java 到 C#:在泛型中扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将此 Java (Android) 代码转换为 c# (MonoDroid),但我不明白

I am trying to convert this Java (Android) code to c# (MonoDroid) but I don't understand the <Item extends OverlayItem>

public class BalloonOverlayView<Item extends OverlayItem> extends FrameLayout

推荐答案

它正在向类型参数添加约束.它类似于 C# 中的 where 子句.

It's adding a constraint to the type parameter. It's analogous to the where clause in C#.

在 Java 中,您有:

In Java, you have:

public class BalloonOverlayView<Item extends OverlayItem> extends FrameLayout

其中 Item 是一个类型参数,它必须子类化或实现类型 OverlayItem.在 C# 中,这将被写为:

Where Item is a type parameter that must subclass or implement type OverlayItem. In C# this would be written as:

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

您可以看到约束是如何移动到最后的,但其他方面类似.在 C# 中的常见做法是命名带有 前缀的类型参数T,所以我会推荐名称 TItem 像这样:

You can see how the constraint is moved to the end, but otherwise analogous. It is very much common practice in C# to name type parameters prefixed with a T, so I would recommend the name TItem like so:

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

这有助于明确类型参数和普通类型之间非常重要的区别.

This helps make clear the pretty important distinction between type parameters and ordinary types.

关于何时想要使用这样的类型约束的讨论,我在之前的回答中详细介绍了这一点.

For a discussion on when you'd want to use type constraints like this, I go into this at length in a previous answer.

这篇关于Java 到 C#:在泛型中扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆