本文實例講述了C#編程獲取實體類屬性名和值的方法。分享給大家供大家參考,具體如下:
遍歷獲得一個實體類的所有屬性名,以及該類的所有屬性的值
//先定義一個類:public class User{ public string name { get; set; } public string gender { get; set; } public string age { get; set; }}//實例化類,并給實列化對像的屬性賦值:User u = new User();u.name = "ahbool";u.gender = "男";//輸出此類的所有屬性名和屬性對應的值Response.Write(getProperties(u));//輸出結果為: name:ahbool,gender:男,age:,//遍歷獲取類的屬性及屬性的值:public string getProperties<T>(T t){ string tStr = string.Empty; if (t == null) { return tStr; } System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); if (properties.Length <= 0) { return tStr; } foreach (System.Reflection.PropertyInfo item in properties) { string name = item.Name; object value = item.GetValue(t, null); if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")) { tStr += string.Format("{0}:{1},", name, value); } else { getProperties(value); } } return tStr;}
希望本文所述對大家C#程序設計有所幫助。
新聞熱點
疑難解答