您的位置:首页 > 编程语言 > C#

C#通过属性名称获取(读取)属性值的方法

2013-09-09 23:03 666 查看

C#通过属性名称获取(读取)属性值的方法

之前在开发一个程序,希望能够通过属性名称读取出属性值,但是由于那时候不熟悉反射,所以并没有找到合适的方法,做了不少的重复性工作啊!

然后今天我再上网找了找,被我找到了,跟大家分享一下。

其实原理并不复杂,就是通过反射利用属性名称去获取属性值,以前对反射不熟悉,所以没想到啊~

不得不说反射是一种很强大的技术。。

下面给代码,希望能帮到有需要的人。

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace PropertyNameGetPropertyValueDemo
7 {
8     class Program
9     {
10         static void Main(string[] args)
11         {
12             Person ps = new Person();
13             ps.Name = "CTZ";
14             ps.Age = 21;
15
16             Demo dm = new Demo();
17             dm.Str = "String";
18             dm.I = 1;
19
20             Console.WriteLine(ps.GetValue("Name"));
21             Console.WriteLine(ps.GetValue("Age"));
22             Console.WriteLine(dm.GetValue("Str"));
23             Console.WriteLine(dm.GetValue("I"));
24         }
25     }
26
27     abstract class AbstractGetValue
28     {
29         public object GetValue(string propertyName)
30         {
31             return this.GetType().GetProperty(propertyName).GetValue(this, null);
32         }
33     }
34
35     class Person : AbstractGetValue
36     {
37         public string Name
38         { get; set; }
39
40         public int Age
41         { get; set; }
42     }
43
44     class Demo : AbstractGetValue
45     {
46         public string Str
47         { get; set; }
48
49         public int I
50         { get; set; }
51     }
52 }


如果觉得上面比较复杂了,可以看下面的简化版。

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace GetValue
7 {
8     class Program
9     {
10         static void Main(string[] args)
11         {
12             Person ps = new Person();
13             ps.Name = "CTZ";
14             ps.Age = 21;
15
16             Console.WriteLine(ps.GetValue("Name"));
17             Console.WriteLine(ps.GetValue("Age"));
18         }
19     }
20
21     class Person
22     {
23         public string Name
24         { get; set; }
25
26         public int Age
27         { get; set; }
28
29         public object GetValue(string propertyName)
30         {
31             return this.GetType().GetProperty(propertyName).GetValue(this, null);
32         }
33     }
34 }


实质语句只有一句:

this.GetType().GetProperty(propertyName).GetValue(this, null);


其他可以忽略。。
http://www.cftea.com/c/2012/10/5657.asp(原文出处,免得变成盗用了)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: