C#扩展方法 - 设计模式 [英] c# Extension methods - design patterns

查看:223
本文介绍了C#扩展方法 - 设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想如果C#扩展方法是基于任何现有的设计模式就知道了。

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

推荐答案

一个设计模式是根本一个众所周知的模式,即当你想要实现X,做Y。在面向对象的语言,如C#一个众所周知的模式是当你想采取行动的对象的状态,调用一个方法上它的一个实例。

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.

这篇关于C#扩展方法 - 设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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