C# Fluent Interface是如何实现的呢?首先我们来看看Fluent Interface,直译过来是 “流畅(流利)的接口”,照字面有点难以理解,那么Fluent Interface是如何实现的呢?下面让我们从代码上向你介绍:
C# Fluent Interface代码实现:
public interface IRect
{
void SetWidth(int width);
void SetHeight(int height);
}
public Rect : IRect
{
private int _width;
private int _height;
public void SetWidth(int width) { this._width = width; }
public void SetHeight(int height){ this_height = height; }
}
public static void Main(string [] args)
{
IRect rect = new Rect();
rect.SetHeight(10);
rect.SetWidth(50);
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
没有什么花俏的东西,一个可设长宽的矩形接口并提供一个简单实现。接下来看看用另一种方式
public interface IRectFluent
{
IRectFluent SetWidth(int width);
IRectFluent SetHeight(int height);
}
public RectFluent : IRectFluent
{
private int _width;
private int _height;
public IRectFluent SetWidth(int width) { this._width = width; return this; }
public IRectFluent SetHeight(int height){ this_height = height; return this; }
}
public static void Main(string [] args)
{
IRectFluent rect = new RectFluent();
rect.SetHeight(10).SetWidth(50); // checkpoint
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
这种“链式"方法调用方式是不是更接近我们人脑的思维方式,更简洁呢。没错, It's Fluent Interface。
个人理解的Fluent Interface 就是 在面向对象编程中,使用某种方式(通常但不限于使用 方法链方式)来实现更具可读性,易用性的编程方式。而方法链的关键之处就是在方法内部调用***要返回调用者本身。
所谓Fluent借助于wikipedia的说法就是‘This style is beneficial due to its ability to provide a more fluid feel to the code."
说到这里,经常使用jquery的朋友肯定感觉很熟悉上面的使用方式。
没错,类似于 $('id').show().css('').fadeOut(); 这种就是一种Fluent Interface实现。
C# Fluent Interface的相关内容就向你介绍到这里,希望对你了解和学习C# Fluent Interface有所帮助。
【编辑推荐】