C# Method<ClassName> 是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/305651/
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 Method<ClassName> mean?
提问by inspite
I've seen this syntax a couple times now, and it's beginning to worry me,
我已经多次看到这种语法,它开始让我担心,
For example:
例如:
iCalendar iCal = new iCalendar();
Event evt = iCal.Create<Event>();
采纳答案by CMS
It's a Generic Method, Create is declared with type parameters, and check this links for more information:
它是一个通用方法, Create 是用类型参数声明的,并查看此链接以获取更多信息:
回答by Jon Skeet
It's calling a generic method - so in your case, the method may be declared like this:
它正在调用一个通用方法 - 所以在你的情况下,该方法可以这样声明:
public T Create<T>()
You can specify the type argument in the angle brackets, just as you would for creating an instance of a generic type:
您可以在尖括号中指定类型参数,就像创建泛型类型的实例一样:
List<Event> list = new List<Event>();
Does that help?
这有帮助吗?
One difference between generic methodsand generic typesis that the compiler can try to infer the type argument. For instance, if your Create
method were instead:
泛型方法和泛型类型之间的一个区别是编译器可以尝试推断类型参数。例如,如果您的Create
方法是:
public T Copy<T>(T original)
you could just call
你可以打电话
Copy(someEvent);
and the compiler would infer that you meant:
编译器会推断你的意思是:
Copy<Event>(someEvent);
回答by Mehrdad Afshari
It's the way you mention a generic method in C#.
这是您在 C# 中提到泛型方法的方式。
When you define a generic method you code like this:
当你定义一个泛型方法时,你的代码是这样的:
return-type MethodName<type-parameter-list>(parameter-list)
When you call a generic method, the compiler usually infers the type parameter from the arguments specified, like this example:
当您调用泛型方法时,编译器通常会从指定的参数中推断出类型参数,如下例所示:
Array.ForEach(myArray, Console.WriteLine);
In this example, if "myArray" is a string array, it'll call Array.ForEach<string> and if it's an int array, it'll call Array.ForEach<int>.
在这个例子中,如果“myArray”是一个字符串数组,它会调用 Array.ForEach<string>,如果它是一个 int 数组,它会调用 Array.ForEach<int>。
Sometimes, it's impossible for the compiler to infer the type from the parameters (just like your example, where there are no parameters at all). In these cases, you have to specify them manually like that.
有时,编译器不可能从参数中推断出类型(就像您的示例一样,根本没有参数)。在这些情况下,您必须像这样手动指定它们。
回答by lvaneenoo
This syntax is just applying generics to a method. It's typically used for scenarios where you want to control the return type of the method. You will find this kind of syntax a lot in code that uses a IoC framework.
此语法只是将泛型应用于方法。它通常用于您想要控制方法的返回类型的场景。您会在使用 IoC 框架的代码中发现很多这种语法。
回答by user33675
It is a generic method that implements the Factory Methodpattern.
它是实现工厂方法模式的通用方法。