栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

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

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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()
   {
 
   }
   /// 
   /// 设置ID,返回this,即jQPerson实例
   /// 
   /// 
   /// 
   public jQPerson setId(string Id)
   {
    this.Id = Id;
    return this;
   }
   /// 
   /// 返回this,即jQPerson实例
   /// 
   /// 
   /// 
   public jQPerson setName(string name)
   {
 
    this.Name = name;
    return this;
   }
   /// 
   /// 返回this,即jQPerson实例
   /// 
   /// 
   /// 
   public jQPerson setAge(int age)
   {
 
    this.Age = age;
    return this;
   }
   /// 
   /// 返回this,即jQPerson实例
   /// 
   /// 
   /// 
   public jQPerson setSex(string sex)
   {
 
    this.Sex = sex;
    return this;
   }
   /// 
   /// 返回this,即jQPerson实例
   /// 
   /// 
   /// 
   public jQPerson setInfo(string info)
   {
 
    this.Info = info;
    return this;
   }
   /// 
   /// tostring输出键值对信息
   /// 
   /// 
   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);
 
 
   }
 
  }
 } 

然后可以对上面进行测试,看方法连缀是否生效:         

/// 
   ///toString 的测试
   ///
   [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("验证此测试方法的正确性。");
   }

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/124602.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号