SoFunction
Updated on 2025-03-06

C# implements jQuery-like method ligation function

The jQuery method is very convenient to use, which can simplify statements and make the code clear and concise. So can C# class methods also implement similar functions? Based on this doubt, I studied the source code of jQuery and found that the function method that requires method concatenation can finally return to the object itself. Since javascript is OK, C# should be OK too.
For verification, write a jQPerson class, and then use method combo to set its ID, Name, Age and other properties. Please see the following code:

 using System;
 using ;
 using ;
 using ;
 using ;
 
 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>
   /// Set the ID, return this, that is, jQPerson instance   /// </summary>
   /// <param name="Id"></param>
   /// <returns></returns>
   public jQPerson setId(string Id)
   {
     = Id;
    return this;
   }
   /// <summary>
   /// Return this, i.e. jQPerson instance   /// </summary>
   /// <param name="name"></param>
   /// <returns></returns>
   public jQPerson setName(string name)
   {
 
     = name;
    return this;
   }
   /// <summary>
   /// Return this, i.e. jQPerson instance   /// </summary>
   /// <param name="age"></param>
   /// <returns></returns>
   public jQPerson setAge(int age)
   {
 
     = age;
    return this;
   }
   /// <summary>
   /// Return this, i.e. jQPerson instance   /// </summary>
   /// <param name="sex"></param>
   /// <returns></returns>
   public jQPerson setSex(string sex)
   {
 
     = sex;
    return this;
   }
   /// <summary>
   /// Return this, i.e. jQPerson instance   /// </summary>
   /// <param name="info"></param>
   /// <returns></returns>
   public jQPerson setInfo(string info)
   {
 
     = info;
    return this;
   }
   /// <summary>
   /// tostring output key-value pair information   /// </summary>
   /// <returns></returns>
   public string toString()
   {
 
    return ("Id:{0},Name:{1},Age:{2},Sex:{3},Info:{4}", , , , , );
 
 
   }
 
  }
 } 

Then you can test the above to see if the method junction takes effect:

/// <summary>
   ///toString test   ///</summary>
   [TestMethod()]
   public void toStringTest()
   {
    jQPerson target = new jQPerson();
    ("2")
     .setName("jack")
     .setAge(26)
     .setSex("man")
     .setInfo("ok");
    string expected = "Id:2,Name:jack,Age:26,Sex:man,Info:ok";
    string actual;
    actual = ();
    (expected, actual);
    //("Verify the correctness of this test method.");   }

From the above operations, we can see that the method connection function does make the code intuitive and concise, and increases readability. You might as well give it a try.