C# 最簡單的鏈式調用例子


鏈式調用,重復使用一個初始化操作,來達到少量代碼表達復雜操作的目的。

直接看例子

 1     public class Student
 2  { 3 private string name; 4 private int age; 5 6 public Student() { } 7 8 public Student setName(string name) 9  { 10 this.name = name; 11  System.Console.WriteLine(name); 12 return this; 13  } 14 15 public Student setAge(int age) 16  { 17 this.age = age; 18  System.Console.WriteLine(age); 19 return this; 20  } 21 }
1 Student person = new Student();
2 person.setAge(12).setName("Jack");//通過鏈式調用

如果SetAge() 和 SetName()的返回類型不是類本身的話,比如返回string、int就不能用這種方式了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM