简体   繁体   English

尖括号在C#中的类名称上有什么作用?

[英]What does angle brackets do on class names in C#?

I know how you can use List<T> for example and decide what that collection is holding. 我知道如何使用List<T>例如,并确定该集合所持有的内容。 That's where T comes in. But I'm not sure I understand the brackets fully. 那就是T出现的地方。但是我不确定我是否完全理解括号。

If I create a class... 如果我创建一个课程...

class MyClass<int> { }

Or instead of int I could use T or object or string or whatever. 或代替int,我可以使用T或对象或字符串或其他任何东西。 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;
}

To instantiate an object from the generic class the standard notation is used, but with the type argument specified after both class names. 为了从泛型类实例化一个对象,使用了标准的符号,但是在两个类名之后都指定了type参数。 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>();

Reference: http://www.pvtuts.com/csharp/csharp-generics 参考: http : //www.pvtuts.com/csharp/csharp-generics

T means Type. T表示类型。 MyClass is a generic class if you use "MyClass". 如果您使用“ MyClass”,则MyClass是泛型类。 More info here 更多信息在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM