c# Extension methods - design patterns

2019-04-06 05:25发布

I would like to know if C# extension method is based on any existing design pattern.

10条回答
闹够了就滚
2楼-- · 2019-04-06 06:14

A design pattern is simply a well known paradigm, i.e. "when you want to achieve X, do Y". A well known paradigm in object-oriented languages such as C# is "when you want to act on the state of an object, call a method on an instance of it".

However, before extension methods were created, you could not call your own method on an instance of an object that you could not add an implementation to (e.g. interfaces because they cannot have implementations, or library classes because they are already compiled). Extension methods fill this gap by allowing you to make methods that appear to be callable on instances of objects, while being defined externally to the implementation of the object.

So yes, arguably extension methods are based on this very simple design pattern, of making methods that act on the state of an object appear to be callable from an instance of it.

查看更多
闹够了就滚
3楼-- · 2019-04-06 06:17

Of course you can use C# extension methods if you want to implement certain design patterns. For example simulate mixins in C#.

查看更多
在下西门庆
4楼-- · 2019-04-06 06:20

The extension methods can be thought as a replacement of the Visitor Pattern. It is also proposed that they can be used as Adapters.

In general languages evolve to make the need of design patterns less necessary. There is a quote for example that Lisp doesn't need design patterns, because everything is built in the language. So the right question will be, what design patterns do extension methods replace?

查看更多
Evening l夕情丶
5楼-- · 2019-04-06 06:22

The closest canonical design patterns is probably the Decorator pattern.

查看更多
啃猪蹄的小仙女
6楼-- · 2019-04-06 06:22

The best matching design pattern to extension method is Facade pattern. My Reason: We usually use extension methods not to introduce a new functionality beyond the target class responsibility, but simplifying using existing target class usage. Because simplifying the target class usage is the Facade pattern concern, extension methods can alternatively be implemented using the Facade pattern. There are some problems in extending and unit testing extension methods. So I think implementing Facade pattern is a better approach against using extension methods. However it is possible to implement some extension methods that wrap the facade interface in order to provide a coding facility for client codes.

查看更多
老娘就宠你
7楼-- · 2019-04-06 06:24

They are not based on an existing design pattern. When this 'feature' was first introduced in Delphi, under the name 'class helpers', Borland even warned users away from them. They were considered a bit of a hack, but now the dust has settled they have found a place of their own.

Like everything else, use when appropriate.

查看更多
登录 后发表回答