C#實現(xiàn)類似jQuery的方法連綴功能
jQuery的方法連綴使用起來非常方便,可以簡化語句,讓代碼變得清晰簡潔。那C#的類方法能不能也實現(xiàn)類似的功能呢?基于這樣的疑惑,研究了一下jQuery的源代碼,發(fā)現(xiàn)就是需要方法連綴的函數(shù)方法最后返回對象本身即可。既然javascript可以,C#應(yīng)該也是可以的。
為了驗證,編寫一個jQPerson類,然后用方法連綴對其ID,Name,Age等屬性進行設(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); } } }
然后可以對上面進行測試,看方法連綴是否生效:
/// <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)文章
WPF調(diào)用WindowsAPI實現(xiàn)屏幕錄制
這篇文章主要為大家詳細介紹了WPF如何調(diào)用WindowsAPI實現(xiàn)屏幕錄制,文中的示例代碼講解詳細,對我們學(xué)習(xí)或工作有一定幫助,感興趣的小伙伴可以了解一下2023-05-05c#數(shù)據(jù)綁定之將datatabel的data添加listView
這篇文章主要介紹了c#將DataTabel的data添加ListView的示例,實現(xiàn)功能是通過響應(yīng)UI Textbox 的值向ListView 綁定新添加的紀(jì)錄。 ,需要的朋友可以參考下2014-04-04