C#获取一个实体类的属性名称、属性值

using System.Reflection;

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

foreach (PropertyInfo pi in t.GetProperties())
{
var name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
var value = pi.GetValue(obj, null);//用pi.GetValue获得值
var type = value?.GetType() ?? typeof(object);//获得属性的类型
if (onlyGetNull&&value!=null) continue;
i++;
sb.AppendFormat("{3} {0} {1}={2} ", type, name, value?.ToString()??"null",i.ToString().PadLeft(2,'0'));
// sb.Append("类型:" + pi.PropertyType.FullName + " 属性名:" + pi.Name + " 值:" + pi.GetValue(obj, null) + "");
}

原文地址:https://www.cnblogs.com/derekhan/p/10102712.html