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

 1 using System.Reflection;
 2 
 3 Type t = obj.GetType();//获得该类的Type
 4 
 5 foreach (PropertyInfo pi in t.GetProperties())
 6 {
 7 var name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
 8 var value = pi.GetValue(obj, null);//用pi.GetValue获得值
 9 var type = value?.GetType() ?? typeof(object);//获得属性的类型
10 if (onlyGetNull&&value!=null) continue;
11 i++;
12 sb.AppendFormat("{3} {0} {1}={2}
", type, name, value?.ToString()??"null",i.ToString().PadLeft(2,'0'));
13 // sb.Append("类型:" + pi.PropertyType.FullName + " 属性名:" + pi.Name + " 值:" + pi.GetValue(obj, null) + "");
14 }
原文地址:https://www.cnblogs.com/yanglang/p/10106781.html