dynamic + 索引器,实现“类”的遍历。


{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

就到这里吧,如果代码有问题,请大家指出!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2026 CODEPRJ.COM