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

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

问题描述

我是新的C#和直接深入到一些修改$ C $下,我收到一个项目。但是,我总是看到code是这样的:

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.

推荐答案

这是一个的泛型类型参数

一个泛型类型参数,您可以指定任意类型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; 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; i >= 0; i--)
    {
        result[j] = array[i];
        j++;
    }
    return result;
}

编译器看到了阵列包含字符串,所以它会返回一个字符串数组。键入字符串代替了 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&LT; T&GT; T 是一个占位符任意类型;这意味着 SampleCollection 可以重新present对象的集合,其中,在创建集合指定的类型。

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

创建一个能容纳的字符串的集合。如上所示,在一个稍微不同的形式的反向方法,可以用来逆转集合的成员。

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天全站免登陆