C# 泛型类的扩展方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2292597/
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
Extension Method for Generic Class
提问by Will
Possible Duplicates:
C# -Generic Extension Method
How do you write a C# Extension Method for a Generically Typed Class
Is it possible to declare extension methods for generic classes?
是否可以为泛型类声明扩展方法?
public class NeedsExtension<T>
{
public NeedsExtension<T> DoSomething(T obj)
{
// ....
}
}
回答by Asad
How do you write a C# Extension Method for a Generically Typed Class
public static class NeedsExtension<T>
{
public static string DoSomething <T>(this MyType<T> v)
{ return ""; }
// OR
public static void DoSomething <T>(this MyType<T> v)
{
//...
}
}
回答by Johannes Rudolph
Yes, but you forgot the this
keyword. Look at Queryable that provides all the LINQ operators on collections.
是的,但您忘记了this
关键字。查看提供集合上所有 LINQ 运算符的 Queryable。
回答by JaredPar
Sure
当然
public static void SomeMethod<T>(this NeedsExtension<T> value) {
...
}
回答by Stan R.
To extend any class
扩展任何类
public static class Extensions
{
public static T DoSomething<T>(this T obj)
{
//...
}
}
To extend a specific generic class
扩展特定的泛型类
public static NeedExtension<T> DoSomething<T>(this NeedExtension<T> obj)
{
//...
}