C#获得对象的所有属性和值

public void GetPros()
        {
            UserInfo userInfo = new UserInfo();
            userInfo.ID = 1;
            userInfo.Name = "jay";
            foreach (System.Reflection.PropertyInfo p in userInfo.GetType().GetProperties())
            {
                Console.WriteLine("Name:{0} Value:{1}", p.Name, p.GetValue(userInfo));
            }
        }

 

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

 

posted on 2017-11-08 10:49  邢帅杰  阅读(13703)  评论(0编辑  收藏  举报