温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C# Fluent Interface怎么实现

发布时间:2021-12-03 10:12:13 来源:亿速云 阅读:126 作者:iii 栏目:编程语言

这篇文章主要介绍“C# Fluent Interface怎么实现”,在日常操作中,相信很多人在C# Fluent Interface怎么实现问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C# 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);  }

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

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  }

这种“链式"方法调用方式是不是更接近我们人脑的思维方式,更简洁呢。没错, 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怎么实现”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI