C# 反射遍历对象

时间:2023-03-09 13:13:49
C# 反射遍历对象

在项目中需要遍历各种对象,可以通过如下方法遍历。

        /// <summary>
/// 返回对象字符串
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public string ReturnString(object obj)
{
StringBuilder str = new StringBuilder();
foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties())
{ str.Append(string.Format("\tName:{0} Value:{1}\r\n", p.Name, p.GetValue(obj, null)));
} return str.ToString(); ; }