C#实现类似jQuery的方法连缀功能

   2015-11-12 0
核心提示:这篇文章主要介绍了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("验证此测试方法的正确性。");
     }

通过以上操作可以看出,方法连缀功能的确使代码变得直观和简洁,增加可阅读性,大家不妨试一试。

 
标签: C# jquery 连缀
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

点击排行