C#遍历自定义对象,获取属性名、属性值,设置属性值

PhysiqueOutModel physiqueOutModel = new PhysiqueOutModel ();//自定义对象

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

foreach (PropertyInfo pi in t.GetProperties())
{
  string name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作

  var value = pi.GetValue(physiqueOutModel, null);//用pi.GetValue获得值

       string newVal = "新值";

      pi.SetValue(physiqueOutModel, newVal);//设置属性值

}

posted @ 2019-07-22 15:09  其善-从之  阅读(3098)  评论(0编辑  收藏  举报