随笔 - 432  文章 - 0  评论 - 15  阅读 - 63万

C#反射技术的简单操作(读取和设置类的属性、属性值)

 

1
2
3
4
5
6
7
8
9
10
11
12
public class A
{
    public int Property1 { get; set; }
}
static void Main(){
    A aa = new A();
    Type type = aa.GetType();//获取类型
    System.Reflection.PropertyInfo propertyInfo = type.GetProperty("Property1");
    propertyInfo.SetValue(aa, 5, null);//给对应属性赋值
    int value = (int)propertyInfo.GetValue(aa, null);
    Console.WriteLine(value );
}

  

少量属性的自动化操作手动添加几下当然是没有问题的,但是属性数量较多的时候敲起这些繁锁的代码可以困了,再说对扩展和维护性造成很多的不便,这时,就需要使用反射来实现了。

要想对一个类型实例的属性或字段进行动态赋值或取值,首先得得到这个实例或类型的Type,微软已经为我们提供了足够多的方法。

首先建立一个测试的类

1
2
3
4
5
6
7
8
public class MyClass
{
    public int one { set; get; }
    public int two { set; get; }
    public int five { set; get; }
    public int three { set; get; }
    public int four { set; get; }
}

  然后编写反射该类的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
MyClass obj = new MyClass();
Type t = typeof(MyClass);
//循环赋值
int i = 0;
foreach (var item in t.GetProperties())
{
    item.SetValue(obj, i, null);
    i += 1;
}
//单独赋值
t.GetProperty("five").SetValue(obj, 11111111, null);
//循环获取
StringBuilder sb = new StringBuilder();
foreach (var item in t.GetProperties())
{
    sb.Append("类型:" + item.PropertyType.FullName + " 属性名:" + item.Name + " 值:" + item.GetValue(obj, null) + "<br />");
}
//单独取值
int five = Convert.ToInt32(t.GetProperty("five").GetValue(obj, null));
sb.Append("单独取five的值:" + five);
string result = sb.ToString();
Response.Write(result);

  

测试显示结果: 
类型:System.Int32 属性名:one 值:0 
类型:System.Int32 属性名:two 值:1 
类型:System.Int32 属性名:five 值:11111111 
类型:System.Int32 属性名:three 值:3 
类型:System.Int32 属性名:four 值:4 
单独取five的值:11111111

了解了类的属性反射使用后,那么方法也是可以这样做的,即t.GetProperties()改为t.GetMethods(),操作方法同上。
 

注:以上代码中如不能直接使用请添加using System.Text;的引用。

posted on   狼来了  阅读(763)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

点击右上角即可分享
微信分享提示