如果能够修改源,为什么要使用扩展方法? [英] Why use an extension method if you are able to modify the source?

查看:62
本文介绍了如果能够修改源,为什么要使用扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以本书为例研究扩展方法,以在C#中扩展Int32(关键字int)的功能结构(在Int32的情况下,我们不能继承结构并更改源代码),我意识到三件事需要扩展方法:

Studying extension methods using the book as an example of expanding the functional structure of an Int32 (int keyword) in C# (we cannot inherit structures and change the source code in the case of Int32), I realized that extension methods are needed for three things:

  1. 如果无法进行继承(如密封类);
  2. 如果无法更改源代码;
  3. 如果有可能但不希望更改类或结构的源代码.

我想知道第三种情况的典型例子是什么.

I wonder what would be a typical example for the third case.

当我自己描述类时,无需使用扩展方法就可以对其进行更改,但是为什么在这种情况下,如果我只需要更改类中的代码,就可能需要使用扩展方法?

When I describe the class myself and I can make changes to it, without using the extension method, but why in this case I might need to use the extension method if I can just change the code in my class?

也就是说,我请您举一个示例,说明何时可以更改代码,但这是不希望的,也是理想的使用扩展方法.

That is, I ask you to give an example when I can change the code, but this is undesirable and desirable use extension method.

推荐答案

有趣的是,我偶然发现了一个可能适用于此的问题.

Funny, I just stumbled upon a question where this might apply to.

您想知道的情况

如果可以修改源代码,为什么还要扩展?

why extend if you can modify the source?

除了基准线以外,还有很多方案:

There are a lot of scenario's but the base line:

如果要添加的功能不是该类的固有组成部分,您想扩展

我给你举个例子

假设您有一个API客户端.您创建了C#代码来使用此客户端.让我们称之为WebClient

Lets say you have a API client. You created C# code to consume this client. Lets call it WebClient

现在,可以说您在另一个MVC Web API应用程序中使用此WebClient来获取远程数据.可以由远程用户A调用.

Now, lets say you use this WebClient in another MVC Web API application to fetch remote data. This can be called by a remote user A.

在某些情况下,您最终会遇到希望根据WebClient的结果从MVC Web API应用程序将特定结果返回到A的情况.

There is a cass in which you'll end up with a situation in which you want to return a specific result to A, from your MVC Web API application based on the result of the WebClient.

此代码将在整个MVC Web API应用程序中使用,因此:考虑 DRY ,您只想编写一次.

This code will be used throughout the MVC Web API Application, so: considering DRY, you want to write it just once.

所以,没有选择的余地:是否在WebClient中.

So, no you have the choice: in the WebClient or not.

考虑一下:

由于您选择了该技术,因此具有MVC Web API特定的功能,但与WebClient的固有属性和功能无关.

The MVC Web API specific functionality is there due to the fact you choose that technology, but it has nothing to do with the intrinsic properties and funtionality of the WebClient.

这是扩展的典型用例.

请参阅:在WEB Api验证时重复代码作为我的灵感来源.

See: Duplication of code when on WEB Api validation as my source of inspiration.

这篇关于如果能够修改源,为什么要使用扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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