当前位置:   article > 正文

C#反射技术的简单操作(读取和设置类的属性)_c#设置类字段属性映射到类

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

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

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

首先建立一个测试的类

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

然后编写反射该类的代码

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


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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/253636
推荐阅读
相关标签
  

闽ICP备14008679号