{dynamic + 索引器,實現“類”的遍歷。
有時候需要用for循環訪問一個類的每個 屬性(公共字段) 時,發現非常麻煩,若取值,就寫成一行一行。
如果對這個類的訪問方法很多,或者說需要索引里面的對象,那才麻煩。
還好,dynamic 關鍵字 + 索引器,就可以幫助實現類的對象索引!
-
首先,什么是dynamic,它和var的區別是什么?
C#是一個強類型的語言,且是編譯型語言(區別於動態語言),編譯語言在編譯器編譯后,變量類型就已經決定。
var 關鍵字會在編譯時自動判斷類型。
1 // 自動識別為 string 類型。 2 var x = "string here.";
dynamic 關鍵字會在運行時自動判斷類型。
// 方法返回類型為 dynamic。 private dynamic Method() { // 運行時,返回的類型實際是 string。 return "string here."; }
-
下面,我們來寫一個完整的Program.cs。
1 using System; 2 3 namespace _test_dynamic 4 { 5 class Program// 程序運行類 6 { 7 static void Main(string[] args)// 程序主方法 8 { 9 // 創建一個學生對象,並初始化內容。 10 Student stu = new Student() 11 { 12 Name = "ddrrqq", 13 Sex = "男", 14 Age = 19, 15 Birth = new DateTime(1992, 11, 1) 16 }; 17 // 顯示用的字符串。 18 string[] printText = new string[4]; 19 20 // 通過for循環遍歷。 21 // stu.Count 得到屬性個數; 22 // 從0開始索引。 23 for (int i = 0; i < stu.Count; i++) 24 { 25 // 遍歷賦值。 26 printText[i] = stu[i].ToString();// 由於 dynamic 禁用了類型檢查,所以沒有 ToString() 方法的智能提示 27 } 28 Console.WriteLine(string.Join("\r\n", printText)); 29 Console.ReadKey(); 30 } 31 } 32 33 public class Student 34 { 35 // 學生類公共屬性計數器。 36 public int Count { get { return 4; } }// 共4個屬性 37 38 // 通過索引器,遍歷公共屬性。 39 public dynamic this[int index] 40 { 41 get 42 { 43 // 遍歷從0 - 3(共4個)。 44 switch (index) 45 { 46 case 0: 47 return this.Name; 48 case 1: 49 return this.Sex; 50 case 2: 51 return this.Birth; 52 case 3: 53 return this.Age; 54 default: 55 return null;// 必須的默認返回 56 } 57 } 58 } 59 60 // 學生類公共屬性。 61 public string Name { get; set; }// 學生姓名 屬性,類型 String 62 public string Sex { get; set; }// 學生性別 屬性,類型 String 63 public DateTime Birth { get; set; }// 學生生日 屬性,類型 DateTime 64 public int Age { get; set; }// 學生年齡 屬性,類型 Int32 65 } 66 }
執行結果:
ddrrqq 男 1992/11/1 0:00:00 19
就到這里吧,如果代碼有問題,請大家指出!
