我的枚举由以下值组成:
private enum PublishStatusses{
NotCompleted,
Completed,
Error
};
我希望能够以用户友好的方式输出这些值。 我不需要再从字符串到值。
我的枚举由以下值组成:
private enum PublishStatusses{
NotCompleted,
Completed,
Error
};
我希望能够以用户友好的方式输出这些值。 我不需要再从字符串到值。
当前回答
根据本文档: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
其他回答
我碰巧是个VB。这是我的版本,结合了DescriptionAttribute方法和扩展方法。一、研究结果:
Imports System.ComponentModel ' For <Description>
Module Module1
''' <summary>
''' An Enum type with three values and descriptions
''' </summary>
Public Enum EnumType
<Description("One")>
V1 = 1
' This one has no description
V2 = 2
<Description("Three")>
V3 = 3
End Enum
Sub Main()
' Description method is an extension in EnumExtensions
For Each v As EnumType In [Enum].GetValues(GetType(EnumType))
Console.WriteLine("Enum {0} has value {1} and description {2}",
v,
CInt(v),
v.Description
)
Next
' Output:
' Enum V1 has value 1 and description One
' Enum V2 has value 2 and description V2
' Enum V3 has value 3 and description Three
End Sub
End Module
基本内容:一个名为EnumType的枚举,有三个值V1, V2和V3。“魔法”发生在控制台。在Sub Main()中调用WriteLine,其中最后一个参数只是v.Description。它为V1返回“1”,为V2返回“V2”,为V3返回“3”。这个description方法实际上是一个扩展方法,定义在另一个名为EnumExtensions的模块中:
Option Strict On
Option Explicit On
Option Infer Off
Imports System.Runtime.CompilerServices
Imports System.Reflection
Imports System.ComponentModel
Module EnumExtensions
Private _Descriptions As New Dictionary(Of String, String)
''' <summary>
''' This extension method adds a Description method
''' to all enum members. The result of the method is the
''' value of the Description attribute if present, else
''' the normal ToString() representation of the enum value.
''' </summary>
<Extension>
Public Function Description(e As [Enum]) As String
' Get the type of the enum
Dim enumType As Type = e.GetType()
' Get the name of the enum value
Dim name As String = e.ToString()
' Construct a full name for this enum value
Dim fullName As String = enumType.FullName + "." + name
' See if we have looked it up earlier
Dim enumDescription As String = Nothing
If _Descriptions.TryGetValue(fullName, enumDescription) Then
' Yes we have - return previous value
Return enumDescription
End If
' Find the value of the Description attribute on this enum value
Dim members As MemberInfo() = enumType.GetMember(name)
If members IsNot Nothing AndAlso members.Length > 0 Then
Dim descriptions() As Object = members(0).GetCustomAttributes(GetType(DescriptionAttribute), False)
If descriptions IsNot Nothing AndAlso descriptions.Length > 0 Then
' Set name to description found
name = DirectCast(descriptions(0), DescriptionAttribute).Description
End If
End If
' Save the name in the dictionary:
_Descriptions.Add(fullName, name)
' Return the name
Return name
End Function
End Module
因为使用Reflection查找描述属性很慢,所以查找也缓存在一个私有Dictionary中,该Dictionary是按需填充的。
(对不起,VB。NET解决方案-将其转换为c#应该相对简单,而我的c#在扩展等新主题上已经生疏了)
也许我遗漏了一些东西,但是枚举。getname有什么问题?
public string GetName(PublishStatusses value)
{
return Enum.GetName(typeof(PublishStatusses), value)
}
编辑:对于用户友好的字符串,你需要通过.resource来完成国际化/本地化,并且使用基于enum键的固定键比使用相同的decorator属性更好。
我用扩展方法做到这一点:
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!";
}
}
}
我创建了一个反向扩展方法来将描述转换回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 static string GetUserFriendlyString(this PublishStatusses status)
{
}