using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine; public class Struct : MonoBehaviour { public static string StructToString(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"; } } }