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

本文转自:https://www.cnblogs.com/xsj1989/p/7802907.html

原文地址:https://www.cnblogs.com/YuanDong1314/p/13050209.html