Why use an extension method if you are able to modify the source? [duplicate]

回眸只為那壹抹淺笑 提交于 2020-01-14 22:49:15

问题


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. If inheritance is not possible, as in the case with sealed classes;
  2. In case of the inability to change the source code;
  3. If it is possible, but undesirable, to change the source code of a class or structure.

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


The question:

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.


回答1:


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

You are wondering about the case of

why extend if you can modify the source?

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

You want to extend if the added functionality is not an intrinsic part of the class

I'll give you an example


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

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.

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.

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

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

Consider this:


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.

This would be a typical use case for extension.

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



来源:https://stackoverflow.com/questions/59598898/why-use-an-extension-method-if-you-are-able-to-modify-the-source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!