扩展方法和静态方法有什么区别? [英] What is difference between extension method and static method?

查看:352
本文介绍了扩展方法和静态方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

扩展方法和静态方法有什么区别?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆