枚举.ToString()-使用snake_case而不是PascalCase



有没有办法将默认的Enum.ToString()转换为snake_case而不是PascalCase?这种变化是全球性的,所以我不必再这样做了。

public enum SpellTypes
{
HorizonFocus
}
public sealed class Settings
{
public Settings(SpellTypes types)
{
TypeString = types.ToString(); // actual: HorizonFocus, expected: horizon_focus
}
public string TypeString { get; }
}

此外

我用Macross.Json.Extensions尝试了以下操作,但它没有将更改应用于TypeString。

[JsonConverter(typeof(JsonStringEnumMemberConverter))]
public enum SpellTypes
{
[EnumMember(Value = "horizon_focus")]
HorizonFocus
}

您可以为所有枚举创建一个扩展方法。

为了提高性能,您可以将snake大小写名称缓存在通用助手类的字典中。

public static string To_snake_case<T>(this T value) where T : Enum
{
return SnakeCaseHelper.Values.TryGetValue(value, out var name) ? name : null;
}
private static class SnakeCaseHelper<T> where T : Enum
{
public static Dictionary<T, string> Values = new();
static SnakeCaseHelper()
{
var names = Enum.GetNames(typeof(T));
var values = (T[])Enum.GetValues(typeof(T));
for (var i = 0; i < values.Length; i++)
Values[values[i]] = GetSnakeCase(names[1]);
}
static string GetSnakeCase(string text)
{
if(text.Length < 2)
return text;
var sb = new StringBuilder();
sb.Append(char.ToLowerInvariant(text[0]));
for(int i = 1; i < text.Length; ++i)
{
char c = text[i];
if(char.IsUpper(c))
{
sb.Append('_');
sb.Append(char.ToLowerInvariant(c));
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}
}

dotnetfiddle

Snake case函数就是从这个答案中得出的。

您可以使用只读类型而不是枚举

public class SpellTypes
{
public static readonly SpellTypes HorizonFocus = new SpellTypes( 1, "Horizon_Focus" );
public static readonly SpellTypes HorizonFocus2 = new SpellTypes( 2, "Horizon_Focus2" );
public static readonly SpellTypes HorizonFocus3 = new SpellTypes( 3, "Horizon_Focus3" );
public readonly int num;
public readonly string name;
private SpellTypes( int num, String name )
{
this.num = num;
this.name = name;
}
}
public sealed class Settings
{
public Settings( SpellTypes types )
{
TypeString = types.name.ToString(); 
}
public string TypeString { get; }
}

最新更新