简体   繁体   English

扩展方法可以有通用参数吗?

[英]Can extension methods have generic parameters?

Can an extension method have a say: List as one of the parameters? 扩展方法可以说:List作为参数之一吗?

public static IEnumerable<XElement> GetSequenceDescendants(this IEnumerable<XElement> elements, params List<XName> names)
        {
            //do something
        }

Is there any restriction on the types of parameters an extension method can have? 扩展方法可以对参数类型有任何限制吗?

The short answer is that an extension method is just a public static method which can be accessed like an instance method of the first parameter (thanks to the this keyword). 简短的回答是扩展方法只是一个公共静态方法,可以像第一个参数的实例方法一样访问 (感谢this关键字)。 This means you can use the same parameters you could use in any static method. 这意味着您可以使用可在任何静态方法中使用的相同参数。

But if you want the parameters to actually be generic you'd need to change your method to this: 但是,如果您希望参数实际上是通用的,则需要将方法更改为:

public static IEnumerable<TElement> GetSequenceDescendants<TElement, TName>(this IEnumerable<TElement> elements, List<TName> names)
{
    //do something
}

You have to specify all the generic arguments in your method definition. 您必须在方法定义中指定所有泛型参数。

Also, you can't use the params keyword with anything but an array, ie params TName[] is okay, but params List<TName> isn't. 此外,除了数组之外,你不能使用params关键字,即params TName[]是可以的,但params List<TName>不是。

There are limits on type inferance (as in when the compiler can guess the generic types from the parameters. The extension methods have one limitation less: you can "dereference" null pointers (you can write and extension method bool IsNullorEmpty(this string) and use it on a null string. 类型感染有限制(例如编译器可以从参数中猜出泛型类型。扩展方法有一个限制:你可以“取消引用”空指针(你可以编写和扩展方法bool IsNullorEmpty(this string)和在空字符串上使用它。

For examples: Linq is full of nice generic extension methods, and you can see a lot of great examples (with smart use of generics) in this question: 例如:Linq充满了很好的通用扩展方法,你可以在这个问题中看到很多很好的例子(巧妙地使用泛型):

What are your favorite extension methods for C#? 你最喜欢的C#扩展方法是什么? (codeplex.com/extensionoverflow) (codeplex.com/extensionoverflow)

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

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