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;
}

 

 

來源:http://www.cnblogs.com/Byrd/archive/2012/08/21/2649518.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM