我的枚举由以下值组成:
private enum PublishStatusses{
NotCompleted,
Completed,
Error
};
我希望能够以用户友好的方式输出这些值。 我不需要再从字符串到值。
我的枚举由以下值组成:
private enum PublishStatusses{
NotCompleted,
Completed,
Error
};
我希望能够以用户友好的方式输出这些值。 我不需要再从字符串到值。
当前回答
如果您只是想在单词之间添加空格,那么简单到
string res = Regex.Replace(PublishStatusses.NotCompleted, "[A-Z]", " $0").Trim();
其他回答
也许我遗漏了一些东西,但是枚举。getname有什么问题?
public string GetName(PublishStatusses value)
{
return Enum.GetName(typeof(PublishStatusses), value)
}
编辑:对于用户友好的字符串,你需要通过.resource来完成国际化/本地化,并且使用基于enum键的固定键比使用相同的decorator属性更好。
这里最简单的解决方案是使用自定义扩展方法(至少在。net 3.5中-您可以将其转换为早期框架版本的静态帮助器方法)。
public static string ToCustomString(this PublishStatusses value)
{
switch(value)
{
// Return string depending on value.
}
return null;
}
我在这里假设您希望返回enum值的实际名称以外的内容(您可以通过简单地调用ToString来获得)。
根据本文档:https://learn.microsoft.com/pt-br/dotnet/api/system.enum.tostring?view=netframework-4.8
可以使用如下格式将枚举数转换为字符串:
public enum Example
{
Example1,
Example2
}
Console.WriteLine(Example.Example1.ToString("g"));
//Outputs: "Example1"
你可以在这个链接中看到所有可能的格式:https://learn.microsoft.com/pt-br/dotnet/api/system.string?view=netframework-4.8
我创建了一个反向扩展方法来将描述转换回enum值:
public static T ToEnumValue<T>(this string enumerationDescription) where T : struct
{
var type = typeof(T);
if (!type.IsEnum)
throw new ArgumentException("ToEnumValue<T>(): Must be of enum type", "T");
foreach (object val in System.Enum.GetValues(type))
if (val.GetDescription<T>() == enumerationDescription)
return (T)val;
throw new ArgumentException("ToEnumValue<T>(): Invalid description for enum " + type.Name, "enumerationDescription");
}
我用扩展方法做到这一点:
public enum ErrorLevel
{
None,
Low,
High,
SoylentGreen
}
public static class ErrorLevelExtensions
{
public static string ToFriendlyString(this ErrorLevel me)
{
switch(me)
{
case ErrorLevel.None:
return "Everything is OK";
case ErrorLevel.Low:
return "SNAFU, if you know what I mean.";
case ErrorLevel.High:
return "Reaching TARFU levels";
case ErrorLevel.SoylentGreen:
return "ITS PEOPLE!!!!";
default:
return "Get your damn dirty hands off me you FILTHY APE!";
}
}
}