天使半只翼

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
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  天使半只翼  阅读(19178)  评论(1编辑  收藏  举报