這篇文章主要介紹了C#實現類似jQuery的方法連綴功能,可以簡化語句,使代碼變得清晰簡單,感興趣的小伙伴們可以參考一下
jQuery的方法連綴使用起來非常方便,可以簡化語句,讓代碼變得清晰簡潔。那C#的類方法能不能也實現類似的功能呢?基于這樣的疑惑,研究了一下jQuery的源代碼,發現就是需要方法連綴的函數方法最后返回對象本身即可。既然javascript可以,C#應該也是可以的。
為了驗證,編寫一個jQPerson類,然后用方法連綴對其ID,Name,Age等屬性進行設置,請看下面的代碼:
- 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>
- /// 設置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("驗證此測試方法的正確性。");
- }
通過以上操作可以看出,方法連綴功能的確使代碼變得直觀和簡潔,增加可閱讀性,大家不妨試一試。
|
新聞熱點
疑難解答