c# Extension methods - design patterns

后端 未结 10 3222
予麋鹿
予麋鹿 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 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.

提交回复
热议问题