C# Fluent Interface概念实例浅析

开发 后端
C# Fluent Interface是什么呢?对于C# Fluent Interface我们是如何实现的呢?那么本文就向你详细介绍相关内容。

C# Fluent Interface是如何实现的呢?首先我们来看看Fluent Interface,直译过来是 “流畅(流利)的接口”,照字面有点难以理解,那么Fluent Interface是如何实现的呢?下面让我们从代码上向你介绍:

C# Fluent Interface代码实现:

  1. public interface IRect  
  2. {  
  3. void SetWidth(int width);  
  4. void SetHeight(int height);  
  5. }  
  6. public Rect : IRect  
  7. {  
  8. private int _width;  
  9. private int _height;  
  10. public void SetWidth(int width) { this._width = width; }  
  11. public void SetHeight(int height){ this_height = height; }  
  12. }  
  13. public static void Main(string [] args)  
  14. {  
  15. IRect rect = new Rect();  
  16. rect.SetHeight(10);  
  17. rect.SetWidth(50);  

没有什么花俏的东西,一个可设长宽的矩形接口并提供一个简单实现。接下来看看用另一种方式

  1. public interface IRectFluent  
  2. {  
  3. IRectFluent SetWidth(int width);  
  4. IRectFluent SetHeight(int height);  
  5. }  
  6. public RectFluent : IRectFluent  
  7. {  
  8. private int _width;  
  9. private int _height;  
  10. public IRectFluent SetWidth(int width) { this._width = width; return this; }  
  11. public IRectFluent SetHeight(int height){ this_height = height; return this; }  
  12. }  
  13. public static void Main(string [] args)  
  14. {  
  15. IRectFluent rect = new RectFluent();  
  16. rect.SetHeight(10).SetWidth(50);  // checkpoint  

这种“链式"方法调用方式是不是更接近我们人脑的思维方式,更简洁呢。没错, 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有所帮助。

【编辑推荐】

  1. C# interface学习经验浅谈
  2. C# interface使用实例分析
  3. 浅析abstract class和interface的不同
  4. 详解abstract class和interface的本质
  5. 关于interface继承来源的讨论
责任编辑:仲衡 来源: 博客园
相关推荐

2009-08-27 13:30:11

C# interfac

2009-08-27 14:12:02

C# interfac

2009-08-27 15:17:18

C# interfacinterface使用

2009-09-14 13:44:14

Lambda ExprC# Lambda

2009-08-18 13:49:21

C# 操作Excel

2009-08-27 17:59:56

C#接口定义

2009-08-17 17:49:20

C# 枚举

2009-09-09 13:57:28

C# XML解析

2009-09-02 10:58:02

C#动态数组

2009-08-24 14:26:42

C# 泛型类

2009-09-09 16:46:59

C# XmlSeria

2009-09-03 14:55:34

C#计算时间间隔

2009-08-19 11:34:06

C#操作Word

2009-08-12 15:26:38

C#读取XML文档

2009-08-19 11:13:49

C#操作Word

2009-08-31 18:38:59

C#写文件

2009-09-01 13:13:28

C#打开Word文档

2009-08-18 16:04:12

C# 操作Excel

2009-08-28 17:34:14

读取word文档

2009-08-19 09:42:52

C#操作Word书签
点赞
收藏

51CTO技术栈公众号