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

C#利用反射,遍历获得一个类的所有属性名,以及该类的实例的所有属性的值

命名空间:System.Reflection
程序集:mscorlib(在 mscorlib.dll 中)

 

C#利用反射,遍历获得一个类的所有属性名,以及该类的实例的所有属性的值

总结:
对应某个类的实例化的对象tc, 遍历获取所有属性(子成员)的方法(采用反射):

Type t = tc.GetType();//获得该类的Type

 

//再用Type.GetProperties获得PropertyInfo[],然后就可以用foreach 遍历了
foreach (PropertyInfo pi in t.GetProperties())
{
    object value1 = pi.GetValue(tc, null));//用pi.GetValue获得值
    string name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
    //获得属性的类型,进行判断然后进行以后的操作,例如判断获得的属性是整数
   if(value1.GetType() == typeof(int))
   {
       //进行你想要的操作
   }
}
注意:

  必须要设置了get 和set方法的属性,反射才能获得该属性

public int Pid
  {
     get { return pid; }
     set { pid = value; }
  }



0
0
 
 



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);

}

 

其它应用请参考:http://www.bitscn.com/pdb/dotnet/200804/138760.html

 

标签: C#, 反射
好文要顶 关注我 收藏该文           
        
C#学习路
关注 - 12
粉丝 - 14
+加关注
1
0
« 上一篇: 大数据预检索处理方式随想
» 下一篇: jQuery mobile 初始化页面的过程

posted on 2013-04-03 16:29 C#学习路 阅读(22355) 评论(1) 编辑 收藏


评论

#1楼27317052013/7/20 22:21:20   

你这看的很仔细啊
支持(0) 反对(0)
2013-07-20 22:21 | 王爱学志  


刷新评论 刷新页面 返回顶部


你可能感兴趣的:(.NET,C#)