博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#反射技术的简单操作(读取和设置类的属性)
阅读量:7030 次
发布时间:2019-06-28

本文共 1747 字,大约阅读时间需要 5 分钟。

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. public class MyClass 
  2. public int one { setget; } 
  3. public int two { setget; } 
  4. public int five { setget; } 
  5. public int three { setget; } 
  6. public int four { setget; } 
 

然后编写反射该类的代码

 
  1. MyClass obj = new MyClass(); 
  2. Type t = typeof(MyClass); 
  3. //循环赋值 
  4. int i = 0; 
  5. foreach (var item in t.GetProperties()) 
  6. item.SetValue(obj, i, null); 
  7. i += 1; 
  8. //单独赋值 
  9. t.GetProperty("five").SetValue(obj, 11111111, null); 
  10. //循环获取 
  11. StringBuilder sb = new StringBuilder(); 
  12. foreach (var item in t.GetProperties()) 
  13. sb.Append("类型:" + item.PropertyType.FullName + " 属性名:" + item.Name + " 值:" + item.GetValue(obj, null) + "<br />"); 
  14. //单独取值 
  15. int five = Convert.ToInt32(t.GetProperty("five").GetValue(obj, null)); 
  16. sb.Append("单独取five的值:" + five); 
  17. string result = sb.ToString(); 
  18. 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
2013-06-05 02:12 阅读(
...) 评论(
...)

转载于:https://www.cnblogs.com/william-lin/archive/2013/06/05/3118233.html

你可能感兴趣的文章
Acm Dima and Lisa的题解
查看>>
2017 ZSTU寒假排位赛 #7
查看>>
MSSQL_打开xp_cmdshell
查看>>
(转)win7英文目录和中文目录,文件夹的别名
查看>>
MySQL进阶
查看>>
mybatis分页 -----PageHelper插件
查看>>
从移动硬盘启动电脑与重装注意事项
查看>>
深入浅出Tomcat系列
查看>>
从网页提取的关键字
查看>>
杭州手持式超声波流量计的特点汇总
查看>>
位运算符
查看>>
【OCP-12c】CUUG 071题库考试原题及答案解析(18)
查看>>
Centos7系统如何不重启系统识别新添加的硬盘?
查看>>
【Unity Shader】自定义材质面板的小技巧
查看>>
icon文件操作
查看>>
BeatSaber节奏光剑双手柄MR教程
查看>>
分组聚合
查看>>
冒泡排序(bubble sort)
查看>>
eclipse新建JSP页面报错:Multiple annotations found at this line解决方法
查看>>
bzoj3685
查看>>