C#實現(xiàn)類似jQuery的方法連綴功能
jQuery的方法連綴使用起來非常方便,可以簡化語句,讓代碼變得清晰簡潔。那C#的類方法能不能也實現(xiàn)類似的功能呢?基于這樣的疑惑,研究了一下jQuery的源代碼,發(fā)現(xiàn)就是需要方法連綴的函數(shù)方法最后返回對象本身即可。既然javascript可以,C#應(yīng)該也是可以的。
為了驗證,編寫一個jQPerson類,然后用方法連綴對其ID,Name,Age等屬性進(jìn)行設(shè)置,請看下面的代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpMethodLikeJQuery
{
public class jQPerson
{
string Id { set; get; }
string Name { set; get; }
int Age { set; get; }
string Sex { set; get; }
string Info { set; get; }
public jQPerson()
{
}
/// <summary>
/// 設(shè)置ID,返回this,即jQPerson實例
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public jQPerson setId(string Id)
{
this.Id = Id;
return this;
}
/// <summary>
/// 返回this,即jQPerson實例
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public jQPerson setName(string name)
{
this.Name = name;
return this;
}
/// <summary>
/// 返回this,即jQPerson實例
/// </summary>
/// <param name="age"></param>
/// <returns></returns>
public jQPerson setAge(int age)
{
this.Age = age;
return this;
}
/// <summary>
/// 返回this,即jQPerson實例
/// </summary>
/// <param name="sex"></param>
/// <returns></returns>
public jQPerson setSex(string sex)
{
this.Sex = sex;
return this;
}
/// <summary>
/// 返回this,即jQPerson實例
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public jQPerson setInfo(string info)
{
this.Info = info;
return this;
}
/// <summary>
/// tostring輸出鍵值對信息
/// </summary>
/// <returns></returns>
public string toString()
{
return string.Format("Id:{0},Name:{1},Age:{2},Sex:{3},Info:{4}", this.Id, this.Name, this.Age, this.Sex, this.Info);
}
}
}
然后可以對上面進(jìn)行測試,看方法連綴是否生效:
/// <summary>
///toString 的測試
///</summary>
[TestMethod()]
public void toStringTest()
{
jQPerson target = new jQPerson();
target.setId("2")
.setName("jack")
.setAge(26)
.setSex("man")
.setInfo("ok");
string expected = "Id:2,Name:jack,Age:26,Sex:man,Info:ok";
string actual;
actual = target.toString();
Assert.AreEqual(expected, actual);
//Assert.Inconclusive("驗證此測試方法的正確性。");
}
通過以上操作可以看出,方法連綴功能的確使代碼變得直觀和簡潔,增加可閱讀性,大家不妨試一試。
相關(guān)文章
詳解C# parallel中并行計算的四種寫法總結(jié)
在C#中,parallel關(guān)鍵字可以用于并行計算。本文為大家總結(jié)了四種C# parallel并行計算的方法,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-11-11
SuperSocket入門--Telnet服務(wù)器和客戶端請求處理
本文的控制臺項目是根據(jù)SuperSocket官方Telnet示例代碼進(jìn)行調(diào)試的,官方示例代碼:Telnet示例。下面跟著小編一起來看下吧2017-01-01
C# 字符串string和內(nèi)存流MemoryStream及比特數(shù)組byte[]之間相互轉(zhuǎn)換
本文主要介紹字符串string和內(nèi)存流MemoryStream及比特數(shù)組byte[]之間相互轉(zhuǎn)換的方法,需要的小伙伴可以參考一下。2016-05-05
C#自定義DataGridViewColumn顯示TreeView
我們可以自定義DataGridView的DataGridViewColumn來實現(xiàn)自定義的列,下面介紹一下如何通過擴展DataGridViewColumn來實現(xiàn)一個TreeViewColumn2015-12-12
.NET(C#):Emit創(chuàng)建異常處理的方法
.NET(C#):Emit創(chuàng)建異常處理的方法,需要的朋友可以參考一下2013-04-04

