在 C# 中,什么是 <T>在方法声明之后? [英] In C#, What is <T> After a Method Declaration?

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

问题描述

我是 VB.Net 的人.(因为我必须这样做,因为签我支票的人是这么说的.:P)我在 Java 中长大,当我有机会时,我通常不会在 C# 中阅读或写作.我今天遇到了一些我从未见过的语法,而且我似乎无法弄清楚.

I'm a VB.Net guy. (because I have to be, because the person who signs my check says so. :P) I grew up in Java and I don't generally struggle to read or write in C# when I get the chance. I came across some syntax today that I have never seen, and that I can't seem to figure out.

在下面的方法声明中,<T > 代表?

In the following method declaration, what does < T > represent?

static void Foo <T >(参数 T[] x)

static void Foo < T >(params T[] x)

我已经看到与声明泛型集合和事物结合使用,但我一生都无法弄清楚它对这个方法做了什么.

I have seen used in conjunction with declaring generic collections and things, but I can't for the life of me figure out what it does for this method.

以防万一,我在考虑一些 C# 脑筋急转弯时遇到了它一>.第六个预告片包含整个代码片段.

In case it matters, I came across it when thinking about some C# brain teasers. The sixth teaser contains the entire code snippet.

推荐答案

这定义了一个 通用方法,它是 泛型,这是在 C# 2.0 中添加到 C# 中的.

This defines a generic method, which is one form of generics, which were added to C# in C# 2.0.

方法 sig 应该是:

The method sig should be:

static void Foo<T>(params T[] x)
{ // ...

这允许您将任意数量的任何(特定)类型的参数传递到方法 Foo 中,并作用于该参数数组.它类似于泛型类型的工作方式,只是范围仅限于方法. 指定传递给方法的参数的类型,因此您可以像这样调用:

This lets you pass any number of arguments of any (specific) type into the method Foo, and it acts on that array of arguments. It's similar to how generic types work, except scoped just to the method. The <T> specifies the type of the argument being passed into the method, so you can call this like:

Foo<MyClass>(myClassInstance, myClassInstance2, mySubclassInstance);

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

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