Cute_demon_attacks/meng_yao/Assets/communal/tool/Struct.cs
舒荣森 83da7e8960 add
2024-11-02 11:19:48 +08:00

89 lines
2.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
public class Struct : MonoBehaviour
{
public static string StructToString<T>(T structObj, int indentLevel)//StructToString 方法接受任何类型的结构体(泛型 T并通过反射获取结构体的所有公共字段和属性。
{
if (structObj == null) return "null";
Type type = structObj.GetType();
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
string indent = new string(' ', indentLevel * 2); // 设置缩进
string result = $"{indent}{type.Name} {{\n";
foreach (FieldInfo field in fields)
{
object fieldValue = field.GetValue(structObj);
result += FormatFieldOrProperty(field.Name, fieldValue, indentLevel);
}
foreach (PropertyInfo property in properties)
{
if (property.CanRead && property.GetIndexParameters().Length == 0) // 确保属性可以读取且不是索引器
{
object propertyValue = null;
try
{
propertyValue = property.GetValue(structObj);
}
catch (Exception ex)
{
propertyValue = $"Error: {ex.Message}";
}
result += FormatFieldOrProperty(property.Name, propertyValue, indentLevel);
}
}
result += $"{indent}}}";
return result;
}
private static string FormatFieldOrProperty(string name, object value, int indentLevel)
{
string indent = new string(' ', indentLevel * 2);
if (value == null)
{
return $"{indent} {name}: null\n";
}
Type valueType = value.GetType();
if (valueType.IsValueType || valueType == typeof(string))
{
return $"{indent} {name}: {value}\n";
}
else if (value is IDictionary dictionary)
{
string dictResult = $"{indent} {name}: {{\n";
foreach (var key in dictionary.Keys)
{
var keyValue = dictionary[key];
dictResult += $"{indent} {key}: {StructToString(keyValue, indentLevel + 2)}\n";
}
dictResult += $"{indent} }}\n";
return dictResult;
}
else if (value is IEnumerable enumerable && !(value is string))
{
string listResult = $"{indent} {name}: [\n";
foreach (var item in enumerable)
{
listResult += $"{indent} {StructToString(item, indentLevel + 2)}\n";
}
listResult += $"{indent} ]\n";
return listResult;
}
else
{
return $"{indent} {name}: {StructToString(value, indentLevel + 1)}\n";
}
}
}