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}\r\n", type, name, value?.ToString()??"null",i.ToString().PadLeft(2,'0')); 13 // sb.Append("類型:" + pi.PropertyType.FullName + " 屬性名:" + pi.Name + " 值:" + pi.GetValue(obj, null) + ""); 14 }