尖括号在C#中的类名称上有什么作用? [英] What does angle brackets do on class names in C#?
问题描述
例如,我知道如何使用 List< T>
并确定该收藏集的内容.那就是T出现的地方.但是我不确定我是否完全理解括号.
I know how you can use List<T>
for example and decide what that collection is holding. That's where T comes in. But I'm not sure I understand the brackets fully.
如果我创建一个课程...
If I create a class...
class MyClass<int> { }
或者代替int,我可以使用T或对象或字符串或其他任何东西.这意味着什么?它会自动变成收藏吗?
Or instead of int I could use T or object or string or whatever. What does that mean? Does it turn into a collection automatically?
推荐答案
泛型类允许类成员使用类型参数.通过添加类型参数,以与泛型方法相同的方式定义它们.在班级名称之后.
Generic classes allow class members to use type parameters. They are defined in the same way as generic methods, by adding a type parameter after the class name.
class Point<T>
{
public T x, y;
}
要从泛型类实例化对象,将使用标准符号,但要在两个类名之后指定type参数.请注意,与泛型方法相反,泛型类必须始终使用显式指定的类型参数实例化.
To instantiate an object from the generic class the standard notation is used, but with the type argument specified after both class names. Note that in contrast to generic methods, a generic class must always be instantiated with the type argument explicitly specified.
Point<short> p = new Point<short>();
参考: http://www.pvtuts.com/csharp/csharp-generics
这篇关于尖括号在C#中的类名称上有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!