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);//设置属性值

}

原文地址:https://www.cnblogs.com/RoyalBlue/p/11225970.html