扩展方法和静态方法有什么区别? [英] What is difference between extension method and static method?
问题描述
扩展方法和静态方法有什么区别?
What is the difference between an extension method and a static method ?
我有两个这样的类:
public static class AClass {
public static int AMethod(string ....)
{
}
}
和
public static class BClass {
public static int BMethod(this string ....)
{
}
}
我可以这样使用
AClass.AMethod('...');
或
'...'.BMethod();
建议哪个?
推荐答案
扩展方法仍然是静态方法。您可以像使用普通的静态方法一样使用它。
An extension method is still a static method. You can use it exactly as you'd use a normal static method.
唯一的区别是扩展方法允许您以类似于它是该类型的一部分,因此您可以编写:
The only difference is that an extension method allows you to use the method in a way that looks like it's part of the type, so you can write:
int result = stringValue.BMethod();
而不是:
int result = BClass.BMethod(stringValue);
这纯粹是作为编译技巧工作的-编译器会看到第一种形式,如果 BClass
是可用的(它具有正确的使用
并且在引用的程序集中),然后将其转换为第二个方法适合您。纯粹是为了方便。
This works purely as a compile "trick" - the compiler sees the first form, and if the BClass
is usable (it has a proper using
and is in a referenced assembly), then it will turn it into the second method's IL for you. It's purely a convenience.
有人建议?
Which is proposed ?
这确实取决于。如果您控制类型,建议您将方法放在类型本身上。通常,这种方法更易于维护。
This really depends. If you control the type, I'd recommend putting the methods on the type itself. This is typically more maintainable.
如果您不控制类型,或者尝试扩展普通类型(例如 IEnumerable< T>
),那么扩展方法可能是一种合理的方法。
If you don't control the type, or you're trying to "extend" a common type (such as IEnumerable<T>
), then extension methods may be a reasonable approach.
但是,如果类型是非常普通的类型,我通常会避免扩展方法,因为它们在智能感知中会变成噪音,从而可能引起额外的混乱。例如,我个人不建议在 System.Object
或 System.String
等上添加扩展方法。
However, if the type is a very common type, I'd typically avoid extension methods, as they become "noise" in intellisense, which in turn can cause extra confusion. For example, I would personally not recommend adding extension methods on System.Object
or System.String
, etc.
这篇关于扩展方法和静态方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!