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(原文出处,免得变成盗用了)

posted @   弎吩锺熱℃  阅读(3965)  评论(1编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示