(client) chore:改进Define的打印函数,使其能打印子类及其递归Define内容

This commit is contained in:
m0_75251201
2025-07-14 14:33:55 +08:00
committed by TheRedApricot
parent d30278da1d
commit 105f4bd964

View File

@ -1,4 +1,9 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml.Linq;
@ -38,21 +43,78 @@ namespace Data
description = xmlDef.Element("description")?.Value;
return false;
}
public override string ToString()
{
// 定义对齐格式(左对齐,固定宽度)
const int labelWidth = -15; // 标签左对齐占15字符
const int valueWidth = -30; // 值左对齐占30字符
var sb = new StringBuilder();
sb.AppendLine($"{"DefName:",labelWidth}{defName,valueWidth}");
sb.AppendLine($"{"Label:",labelWidth}{label,valueWidth}");
sb.AppendLine($"{"Description:",labelWidth}{description,valueWidth}");
sb.AppendLine($"{"PackID:",labelWidth}{packID,valueWidth}");
// 使用反射获取当前类的所有字段和属性
var fieldsAndProperties = GetAllFieldsAndProperties(this);
foreach (var member in fieldsAndProperties)
{
var name = member.Name;
var value = GetValue(member, this);
if (value is IList list && list.Count > 0) // 如果是列表类型
{
sb.AppendLine($"{name}:");
foreach (var item in list)
{
sb.AppendLine($" - {FormatValue(item)}");
}
}
else if (value is Define defineObject) // 如果是继承自 Define 的子类
{
if (!string.IsNullOrEmpty(defineObject.defName))
{
sb.AppendLine($"{name}: {defineObject.defName}");
}
else
{
sb.AppendLine($"{name}:");
sb.AppendLine(Indent(defineObject.ToString(), " "));
}
}
else
{
sb.AppendLine($"{name}: {FormatValue(value)}");
}
}
return sb.ToString();
}
private static IEnumerable<MemberInfo> GetAllFieldsAndProperties(object obj)
{
var type = obj.GetType();
return type.GetFields(BindingFlags.Public | BindingFlags.Instance)
.Cast<MemberInfo>()
.Concat(type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Cast<MemberInfo>());
}
private static object GetValue(MemberInfo member, object obj)
{
switch (member)
{
case FieldInfo field:
return field.GetValue(obj);
case PropertyInfo property:
return property.GetValue(obj);
default:
throw new ArgumentException("Unsupported member type.");
}
}
private static string FormatValue(object value)
{
return value?.ToString() ?? "null";
}
private static string Indent(string text, string prefix)
{
return string.Join(Environment.NewLine, text.Split('\n').Select(line => prefix + line));
}
}
}