扩展方法VS静态工具类静态、工具、方法、VS

2023-09-02 20:48:57 作者:尘缘若梦

我在寻找一些优点和缺点,使用了静态工具类扩展方法在C#应用程序。

I'm looking for some pros and cons for using extension methods over static utility classes in a C# app.

例如,在扩展方法列加是通过调用类的名字,而不是像StringUtils的东西的舒适。但是一个反面的是,它可以模糊分辨什么是在框架中,什么不是行。

For instance, a plus in the extension methods column is the convinience of calling by the class name rather than something like "StringUtils". But a con would be that it can blur the lines between what is in the framework and what isn't.

推荐答案

我会说一个的 PRO 的是,它模糊了区别什么是在框架中,什么不是行:可以用自己的code一样自然框架code,对框架类型进行操作。

I would say that a pro is that it blurs the lines between what is in the framework and what isn't: you can use your own code as naturally as framework code, operating on framework types.

扩展方法不宜随意使用的,当然 - 它不喜欢的所有的静态方法应该成为扩展方法

Extension methods shouldn't be used arbitrarily, of course - it's not like all static methods should become extension methods.

我试图把它看成该方法是否是对的第一个参数逻辑操作。难道是有意义的实例方法,如果你能够将它作为一个实例方法?

I try to think of it as whether the method is logically operating "on" its first parameter. Would it make sense as an instance method, if you were able to include it as an instance method?

一个骗子,你可能不知道的:如果扩展类型后增加了它是适用相同的参数名称相同的实例方法,您的电话code将透明地开始调用该实例的方法下一个一次重新编译。例如,获得 CopyTo从 在.NET 4 ...我倒是previously写了 CopyTo从扩展方法,然后将不被调用。有没有预警,这是发生的,所以你必须对你的警惕。

A "con" which you may not be aware of: if the extended type later adds an instance method of the same name which is applicable with the same parameters, your calling code will transparently start calling that instance method next time you recompile. For example, Stream gained CopyTo in .NET 4... I'd previously written a CopyTo extension method, which then wouldn't be called. There's no warning that this is occurring, so you have to be on your guard.

警告:扩展方法都没有存在了足够长的时间来真正成为公认的最佳实践。你应该衡量所有意见(甚至 - 或许尤其是 - 我自己的)。仔细

One caveat: extension methods haven't been around for long enough for best practices to really become established. You should weigh up all opinions (even - or perhaps especially - my own ones) carefully.