什么是 <T>在 C# 中表示 [英] What does <T> denote in C#

查看:21
本文介绍了什么是 <T>在 C# 中表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C# 新手,直接潜心修改我收到的项目的一些代码.但是,我一直看到这样的代码:

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>

我无法理解

<T> 

意思也不叫什么.

如果有人愿意帮我命名这个概念的名称,我可以在线搜索.然而,我现在一无所知.

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.

推荐答案

这是一个 通用类型参数.

泛型类型参数允许您在编译时为方法指定任意类型 T,而无需在方法或类声明中指定具体类型.

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.

例如:

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);

将在{ "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;
}

编译器看到 array 包含字符串,所以它返回一个字符串数组.类型 string 被替换为 T 类型参数.

The compiler sees that array contains strings, so it returns an array of strings. Type string is substituted for the T type parameter.

泛型类型参数也可用于创建泛型类.在您给出的 SampleCollection 示例中,T 是任意类型的占位符;这意味着 SampleCollection 可以表示一个对象集合,其类型是您在创建集合时指定的.

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.

所以:

var collection = new SampleCollection<string>();

创建一个可以容纳字符串的集合.上面说明的 Reverse 方法以稍微不同的形式,可用于反转集合的成员.

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.

这篇关于什么是 &lt;T&gt;在 C# 中表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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