C#編程獲取實體類屬性名和值的方法示例。本站提示廣大學習愛好者:(C#編程獲取實體類屬性名和值的方法示例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#編程獲取實體類屬性名和值的方法示例正文
本文實例講述了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;
}
PS:這裡再為大家推薦一款本站的C#相關工具供大家參考使用:
JSON在線轉換成C#實體類工具:
http://tools.jb51.net/code/json2csharp
更多關於C#相關內容感興趣的讀者可查看本站專題:《C#數據結構與算法教程》、《C#遍歷算法與技巧總結》、《C#數組操作技巧總結》及《C#面向對象程序設計入門教程》
希望本文所述對大家C#程序設計有所幫助。