<T>在C#中表示什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9857180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does <T> denote in C#
提问by Yash Desai
I'm new to C# and directly diving into modifying some code for a project I received. However, I keep seeing code like this :
我是 C# 新手,直接潜入修改我收到的项目的一些代码。但是,我一直看到这样的代码:
class SampleCollection<T>
and I cannot make sense of what the
我无法理解
<T>
means nor what it is called.
意思也不叫什么。
If anyone would care to help me just name what this concept is called, I can search it online. However, I'm clueless as of now.
如果有人愿意帮我命名这个概念的名称,我可以在线搜索。然而,我现在一无所知。
采纳答案by Robert Harvey
It is a Generic Type Parameter.
它是一个通用类型参数。
A generic type parameter allows you to specify an arbitrary type T to a method at compile-time, without specifying a concrete type in the method or class declaration.
泛型类型参数允许您在编译时为方法指定任意类型 T,而无需在方法或类声明中指定具体类型。
For example:
例如:
public T[] Reverse<T>(T[] array)
{
var result = new T[array.Length];
int j=0;
for(int i=array.Length - 1; i>= 0; i--)
{
result[j] = array[i];
j++;
}
return result;
}
reverses the elements in an array. The key point here is that the array elements can be of any type, and the function will still work. You specify the type in the method call; type safety is still guaranteed.
反转数组中的元素。这里的关键是数组元素可以是任何类型,函数仍然可以工作。您在方法调用中指定类型;类型安全还是有保障的。
So, to reverse an array of strings:
因此,要反转字符串数组:
string[] array = new string[] { "1", "2", "3", "4", "5" };
var result = reverse(array);
Will produce a string array in resultof { "5", "4", "3", "2", "1" }
将在resultof 中产生一个字符串数组{ "5", "4", "3", "2", "1" }
This has the same effect as if you had called an ordinary (non-generic) method that looks like this:
这与调用如下所示的普通(非泛型)方法具有相同的效果:
public string[] Reverse(string[] array)
{
var result = new string[array.Length];
int j=0;
for(int i=array.Length - 1; i >= 0; i--)
{
result[j] = array[i];
j++;
}
return result;
}
The compiler sees that arraycontains strings, so it returns an array of strings. Type stringis substituted for the Ttype parameter.
编译器看到它array包含字符串,所以它返回一个字符串数组。类型string替换了T类型参数。
Generic type parameters can also be used to create generic classes. In the example you gave of a SampleCollection<T>, the Tis a placeholder for an arbitrary type; it means that SampleCollectioncan represent a collection of objects, the type of which you specify when you create the collection.
泛型类型参数也可用于创建泛型类。在您给出的 a 示例中SampleCollection<T>, theT是任意类型的占位符;这意味着SampleCollection可以表示对象的集合,您在创建集合时指定其类型。
So:
所以:
var collection = new SampleCollection<string>();
creates a collection that can hold strings. The Reversemethod illustrated above, in a somewhat different form, can be used to reverse the collection's members.
创建一个可以容纳字符串的集合。Reverse上面说明的方法,以稍微不同的形式,可用于反转集合的成员。
回答by Kendall Frey
This feature is known as generics. http://msdn.microsoft.com/en-us/library/512aeb7t(v=vs.100).aspx
此功能称为泛型。http://msdn.microsoft.com/en-us/library/512aeb7t(v=vs.100).aspx
An example of this is to make a collection of items of a specific type.
这方面的一个例子是制作特定类型的项目的集合。
class MyArray<T>
{
T[] array = new T[10];
public T GetItem(int index)
{
return array[index];
}
}
In your code, you could then do something like this:
在您的代码中,您可以执行以下操作:
MyArray<int> = new MyArray<int>();
In this case, T[] arraywould work like int[] array, and public T GetItemwould work like public int GetItem.
在这种情况下,T[] array将工作一样int[] array,并且public T GetItem将工作一样public int GetItem。
回答by BrunoLM
It is a generic type parameter, see Genericsdocumentation.
它是一个泛型类型参数,请参阅泛型文档。
Tis not a reserved keyword. T, or any given name, means a type parameter. Check the following method (just as a simple example).
T不是保留关键字。T,或任何给定的名称,表示一个类型参数。检查以下方法(仅作为简单示例)。
T GetDefault<T>()
{
return default(T);
}
Note that the return type is T. With this method you can get the default value of any type by calling the method as:
请注意,返回类型是T. 使用此方法,您可以通过调用该方法来获取任何类型的默认值:
GetDefault<int>(); // 0
GetDefault<string>(); // null
GetDefault<DateTime>(); // 01/01/0001 00:00:00
GetDefault<TimeSpan>(); // 00:00:00
.NET uses generics in collections, ... example:
.NET 在集合中使用泛型,...例如:
List<int> integerList = new List<int>();
This way you will have a list that only accepts integers, because the class is instancited with the type T, in this case int, and the method that add elements is written as:
这样你就会有一个只接受整数的列表,因为这个类是用 type 实例化的T,在这种情况下是int,并且添加元素的方法被写成:
public class List<T> : ...
{
public void Add(T item);
}
Some more information about generics.
关于泛型的更多信息。
You can limit the scope of the type T.
您可以限制类型的范围T。
The following example only allows you to invoke the method with types that are classes:
以下示例仅允许您调用具有类类型的方法:
void Foo<T>(T item) where T: class
{
}
The following example only allows you to invoke the method with types that are Circleor inherit from it.
以下示例仅允许您调用具有Circle或继承自它的类型的方法。
void Foo<T>(T item) where T: Circle
{
}
And there is new()that says you can create an instance of Tif it has a parameterless constructor. In the following example Twill be treated as Circle, you get intellisense...
还有new()就是说T如果它有一个无参数的构造函数,你可以创建一个实例。在以下示例T中将被视为Circle,您将获得智能感知...
void Foo<T>(T item) where T: Circle, new()
{
T newCircle = new T();
}
As Tis a type parameter, you can get the object Typefrom it. With the Typeyou can use reflection...
作为T类型参数,您可以从中获取对象Type。随着Type你可以使用反射...
void Foo<T>(T item) where T: class
{
Type type = typeof(T);
}
As a more complex example, check the signature of ToDictionaryor any other Linq method.
作为更复杂的示例,请检查ToDictionary或任何其他 Linq 方法的签名。
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
There isn't a T, however there is TKeyand TSource. It is recommended that you always name type parameters with the prefix Tas shown above.
没有T,但是有TKey和TSource。建议您始终使用T如上所示的前缀命名类型参数。
You could name TSomethingFooif you want to.
TSomethingFoo如果你愿意,你可以命名。

