闽公网安备 35020302035485号
public static void PrintProperties(object obj, int indentLevel, ref StringBuilder sb)
{
try
{
// 堆代码 duidaima.com
var type = obj.GetType();
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
string[] arr = newstring[] { "", "", "" };
if (property.PropertyType.IsClass && property.PropertyType != typeof(string))
{
varvalue = property.GetValue(obj);
if (value == null)
{
value = Activator.CreateInstance(property.PropertyType);
}
// 判断属性的类型是否为泛型类型
if (property.PropertyType.IsGenericType)
{
// 获取属性的泛型类型定义
var typeDefinition = property.PropertyType.GetGenericTypeDefinition();
Type[] typeArgs = value.GetType().GetGenericArguments();
var temp = Activator.CreateInstance(typeArgs[0]);
// 判断泛型类型是否为 IEnumerable<T>
if (typeDefinition == typeof(IEnumerable<>))
{
arr[0] = "IEnumerable<";
arr[1] = typeArgs[0].Name;
arr[2] = "> ";
}
elseif (typeDefinition == typeof(List<>))
{
arr[0] = "List<";
arr[1] = typeArgs[0].Name;
arr[2] = "> ";
}
// 判断泛型类型是否为 ICollection<T>
elseif (typeDefinition == typeof(ICollection<>))
{
arr[0] = "ICollection<";
arr[1] = typeArgs[0].Name;
arr[2] = "> ";
}
elseif (typeDefinition == typeof(Dictionary<,>))
{
arr[0] = "Dictionary<";
arr[1] = string.Join(",", typeArgs.Select(t => t.Name));
arr[2] = "> ";
}
sb.Append(newstring(' ', indentLevel * 4));
sb.AppendLine("- " + string.Join("", arr) + property.Name);
PrintProperties(temp, indentLevel + 1, ref sb);
}
else
{
arr[0] = "";
arr[1] = property.PropertyType.Name;
arr[2] = " ";
sb.Append(newstring(' ', indentLevel * 4));
sb.AppendLine("- " + string.Join("", arr) + property.Name);
PrintProperties(value, indentLevel + 1, ref sb);
}
}
else
{
arr[0] = "";
arr[1] = property.PropertyType.Name;
arr[2] = " ";
sb.Append(newstring(' ', indentLevel * 4));
sb.AppendLine("- " + string.Join("", arr) + property.Name);
}
}
}
catch (Exception ex)
{
throw;
}
}
示例图: