遗忘的代码

在编程中寻找艺术,享受新的体验。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

c# 如何通过反射 获取\设置属性值


//定义类
public class MyClass
{
public int Property1 { get; set; }
}
static void Main()
{
MyClass tmp_Class = new MyClass();
tmp_Class.Property1 = 2;
Type type = tmp_Class.GetType(); //获取类型
System.Reflection.PropertyInfo propertyInfo = type.GetProperty("Property1"); //获取指定名称的属性
int value_Old = (int)propertyInfo.GetValue(tmp_Class, null); //获取属性值
Console.WriteLine(value_Old);
propertyInfo.SetValue(tmp_Class, 5, null); //给对应属性赋值
int value_New = (int)propertyInfo.GetValue(tmp_Class, null);
Console.WriteLine(value_New);

}

posted on 2014-12-08 12:51  遗忘的代码  阅读(219)  评论(0编辑  收藏  举报