遍历类

转处http://www.cnblogs.com/love2wllw/archive/2010/01/28/1658719.html

先获取类的Type
Type type = this.GetType();
//再用Type.GetProperties获得PropertyInfo[],然后就可以用foreach 遍历了
foreach (System.Reflection.PropertyInfo PInfo in type.GetProperties())
{
            //用PInfo.GetValue获得值
            string val = Convert.ToString(PInfo.GetValue(this, null));
            //获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
            string name = PInfo.Name;
            //自己想要的操作
}

根据属性名字符串设置属性值:
string PropertyName=”Username”;
object obj=未知的数据;

//获取属性对象
PropertyInfo ProInfo = this.GetType().GetProperty(PropertyName);

//获取属性的数据类型
Type ProType = ProInfo.PropertyType;

//设置属性值
ProInfo.SetValue(this, Convert.ChangeType(obj, ProType), null);

原文地址:https://www.cnblogs.com/zhangji/p/2426582.html