简体   繁体   English

非泛型类型中的通用方法

[英]Generic methods in non-generic types

When you have a method like: 当你有一个方法,如:

public static T DoSomething<T> ( params T [ ] input )

C# lets you to call it without specifying the T, like: C#允许您在不指定T的情况下调用它,如:

DoClass.DoSomething ( "1", "2", "3" );

Does the compiler figure out T by what's passed to it? 编译器是否根据传递给它的方法计算出T?

Is this a good convention (to leave out T in this case)? 这是一个很好的约定(在这种情况下省略T)?

Yes, the compiler can infer the generic type parameter in the majority of cases. 是的,编译器可以在大多数情况下推断泛型类型参数。 (One exceptin being when your type is a lambda expression, if I remember right.) (除非是你的类型是lambda表达式,如果我没记错的话。)

It is generally considered perfectly good practice to omit the generic parameters when they can be inferred. 通常认为在推断出通用参数时省略通用参数是非常好的做法。 In fact, I would say that it increases readability a certain amount (specifying them is often quite redundant). 事实上,我会说它增加了一定的可读性(指定它们通常是多余的)。

Yes, the compiler will typically figure out the type. 是的,编译器通常会找出类型。 It's called "type inference". 它被称为“类型推断”。

And yes, it's a best practice to leave T out at the call site. 是的,将T留在呼叫站点是最佳做法。 The less code you write, the less code someone has to read and understand later. 您编写的代码越少,以后需要阅读和理解的代码越少。

If you have ReSharper , it will do a good job of showing you where you can and can't get away with removing the at the call site. 如果你有ReSharper ,那么它会很好地向你展示你可以去哪里,并且无法通过移除呼叫站点来逃脱。 Otherwise you can try taking it out, and if the code compiles, then you didn't need it. 否则你可以尝试将其取出,如果代码编译,那么你不需要它。

Yes, when the compiler can figure out what T is supposed to be, it is redundant to specify it. 是的,当编译器能够确定T应该是什么时,指定它是多余的。 I find this a great feature, because it gets tedious and hard to read when the type name is always listed (especially with long names). 我发现这是一个很棒的功能,因为当类型名称总是列出时(特别是长名称),它会变得乏味且难以阅读。

As many people have mentioned, this is due to generic parameter type inference by the compiler. 正如许多人所提到的,这是由于编译器的泛型参数类型推断。 It discovers the type directly by the first parameter. 它通过第一个参数直接发现类型。

One other thing - if you read the design guidelines for .net libraries, it's actually recommended to write ALL of your generic methods in a way that the types can be inferred. 另一件事 - 如果您阅读.net库的设计指南,实际上建议您以可以推断类型的方式编写所有通用方法。 Non-inferrable generic methods are considered more difficult to understand, and should be avoided when possible, according to the design guidelines book. 根据设计指南书,不可推理的通用方法被认为更难理解,应尽可能避免。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM