你有没有发现什么扩展方法的好处? [英] What Advantages of Extension Methods have you found?

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

问题描述

C#的非信徒是问我是什么目的,扩展方法了。我解释说,然后你可以添加新方法已经被定义的对象,尤其是当你不拥有/控制源到原始对象。

A "non-believer" of C# was asking me what the purpose to extension methods was. I explained that you could then add new methods to objects that were already defined, especially when you don't own/control the source to the original object.

他提出了为什么不只是添加一个方法来自己的类?我们一直兜兜转转,(一个好办法)。我一般的回答是,这是在工具区的另一种工具,而他的反应是它是一个工具,一个无用的垃圾......但我想我会得到一个更开明的答案。

He brought up "Why not just add a method to your own class?" We've been going round and round (in a good way). My general response is that it is another tool in the toolbelt, and his response is it is a useless waste of a tool... but I thought I'd get a more "enlightened" answer.

什么是你使用扩展方法,你可以没有(或不应该)使用的方法添加到您自己的类?某些情况下

What are some scenarios that you've used extension methods that you couldn't have (or shouldn't have) used a method added on to your own class?

推荐答案

我觉得写code时的扩展方法有很大的帮助,如果您添加扩展方法的基本类型,你会得到他们quicky在智能感知。

I think extension methods help a lot when writing code, if you add extension methods to basic types you'll get them quicky in the intellisense.

我有一个格式提供商格式的文件大小。要使用它,我需要写:

I have a format provider to format a file size. To use it I need to write:

Console.WriteLine(String.Format(new FileSizeFormatProvider(), "{0:fs}", fileSize));

创建一个扩展方法我可以这样写:

Creating an extension method I can write:

Console.WriteLine(fileSize.ToFileSize());

清晰,更简单。

这篇关于你有没有发现什么扩展方法的好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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