I'm new to C# and directly diving into modifying some code for a project I received. However, I keep seeing code like this :

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.

推荐答案

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.

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 result of { "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 array contains strings, so it returns an array of strings. Type string is substituted for the T type parameter.


Generic type parameters can also be used to create generic classes. In the example you gave of a SampleCollection<T>, the T is a placeholder for an arbitrary type; it means that SampleCollection can represent a collection of objects, the type of which you specify when you create the collection.

So:

var collection = new SampleCollection<string>();

creates a collection that can hold strings. The Reverse method illustrated above, in a somewhat different form, can be used to reverse the collection's members.

.net相关问答推荐

为什么Linq中的运算符逻辑不匹配结果,当值为0或在VB. NET中没有

从Couchbase删除_txn文档的推荐方法?""

DI通过对象的接口而不是实际类型来解析服务

避免函数和其他对象之间的相互递归的模式?

如何查询 DOTNET_CLI_TELEMETRY_OPTOUT 是否永久设置为 TRUE?

向从 .NET 序列化的对象添加 Xml 属性

C#.Net 中的可选返回

在 WebApi 中需要 SSL?

C# 中的批量更新

如何创建 LINQ to SQL 事务?

为什么 C# 不允许像 C++ 这样的非成员函数

File.ReadAllLines() 和 File.ReadAllText() 有什么区别?

运算符重载 ==, !=, Equals

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") 返回上午时间而不是下午时间?

.NET 反射的成本是多少?

SQLParameter 如何防止 SQL 注入?

清除文件内容

带有嵌套控件的设计模式

如何在 C# 中使用迭代器反向读取文本文件

判断数据表中是否包含空值的最佳方法