c# Extension methods - design patterns

后端 未结 10 3219
予麋鹿
予麋鹿 2021-02-20 16:33

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

相关标签:
10条回答
  • 2021-02-20 16:53

    No, but extension methods are excellent for implementing certain GoF design patterns (e.g., Prototype).

    0 讨论(0)
  • 2021-02-20 16:57

    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?

    0 讨论(0)
  • 2021-02-20 16:58

    The closest canonical design patterns is probably the Decorator pattern.

    0 讨论(0)
  • 2021-02-20 16:59

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

    0 讨论(0)
  • 2021-02-20 17:02

    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.

    0 讨论(0)
  • 2021-02-20 17:03

    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.

    0 讨论(0)
提交回复
热议问题