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(原文出處,免得變成盜用了)


免責聲明!

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



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