C# Fluent Interface概念實(shí)例淺析
C# Fluent Interface是如何實(shí)現(xiàn)的呢?首先我們來看看Fluent Interface,直譯過來是 “流暢(流利)的接口”,照字面有點(diǎn)難以理解,那么Fluent Interface是如何實(shí)現(xiàn)的呢?下面讓我們從代碼上向你介紹:
C# Fluent Interface代碼實(shí)現(xiàn):
- 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);
- }
沒有什么花俏的東西,一個(gè)可設(shè)長(zhǎng)寬的矩形接口并提供一個(gè)簡(jiǎn)單實(shí)現(xiàn)。接下來看看用另一種方式
- 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
- }
這種“鏈?zhǔn)?方法調(diào)用方式是不是更接近我們?nèi)四X的思維方式,更簡(jiǎn)潔呢。沒錯(cuò), It's Fluent Interface。
個(gè)人理解的Fluent Interface 就是 在面向?qū)ο缶幊讨?,使用某種方式(通常但不限于使用 方法鏈方式)來實(shí)現(xiàn)更具可讀性,易用性的編程方式。而方法鏈的關(guān)鍵之處就是在方法內(nèi)部調(diào)用***要返回調(diào)用者本身。
所謂Fluent借助于wikipedia的說法就是‘This style is beneficial due to its ability to provide a more fluid feel to the code."
說到這里,經(jīng)常使用jquery的朋友肯定感覺很熟悉上面的使用方式。
沒錯(cuò),類似于 $('id').show().css('').fadeOut(); 這種就是一種Fluent Interface實(shí)現(xiàn)。
C# Fluent Interface的相關(guān)內(nèi)容就向你介紹到這里,希望對(duì)你了解和學(xué)習(xí)C# Fluent Interface有所幫助。
【編輯推薦】