add AutoToString

This commit is contained in:
Mikhail 2023-06-22 10:50:47 +08:00
parent 3c3e856eff
commit 757283f4e7

View File

@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace DCFApixels.DragonECS
{
@ -37,6 +39,24 @@ namespace DCFApixels.DragonECS
}
#endregion
#region AutoToString
public static string AutoToString<T>(this T self, bool isWriteName = true) where T : struct
{
return AutoToString(self, typeof(T), isWriteName);
}
private static string AutoToString(object target, Type type, bool isWriteName)
{
var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
string[] values = new string[fields.Length];
for (int i = 0; i < fields.Length; i++)
values[i] = fields[i].GetValue(target).ToString();
if(isWriteName)
return $"{type.Name}({string.Join(", ", values)})";
else
return $"({string.Join(", ", values)})";
}
#endregion
#region GetName
public static string GetName<T>() => GetName(typeof(T));
public static string GetName(Type type) => type.TryGetCustomAttribute(out DebugNameAttribute atr) ? atr.name : GetGenericTypeName(type);