扩展方法与静态实用程序类 [英] Extension Methods vs Static Utility Class

查看:93
本文介绍了扩展方法与静态实用程序类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一些在C#应用程序中使用扩展方法的静态实用程序类的优缺点。

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

例如,在扩展方法列中有一个加号是调用类名称而不是像StringUtils的方便。但是一个con可能会模糊框架中的内容与什么不相符。

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 是,它模糊了框架中的内容和什么不是:您可以使用自己的代码作为框架代码,在框架类型上运行。

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?

您可能不知道的con:如果扩展类型稍后添加一个相同名称的实例方法,该方法适用于相同的参数,您的调用代码将在下次重新编译时透明地开始调用该实例方法。例如, Stream 获得 CopyTo 在.NET 4 ...我以前写过一个 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.

这篇关于扩展方法与静态实用程序类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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