我的枚举由以下值组成:

private enum PublishStatusses{
    NotCompleted,
    Completed,
    Error
};

我希望能够以用户友好的方式输出这些值。 我不需要再从字符串到值。


当前回答

我创建了一个反向扩展方法来将描述转换回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");
}

其他回答

我已经迟到7年了:-)但我相信这个话题经常被访问。所以我想在咖啡里加一点糖:

那么“F”格式字符串说明符呢?

PublishStatusses[] ps = Enum.GetValues<PublishStatusses>();
ps.ToList().ForEach(c => Console.Write($"{c:F} "));

不需要任何显式的函数调用。

事实上,甚至不需要任何格式说明符。 在将变量赋值给字符串的情况下,ToString()执行以下工作:

string foo = PublishStatusses.Error.ToString(); // or ToString("F")

如果它要在CamelCase字符串的单词之间插入空格,你可以使用正则表达式:

Regex.Replace(foo, "(\\B[A-Z])", " $1")

另一篇文章是Java。在c#中,你不能把方法放在枚举中。

就像这样做:

PublishStatusses status = ...
String s = status.ToString();

如果您想为枚举值使用不同的显示值,您可以使用Attributes和Reflection。

这是对Ray Booysen的代码的更新,使用通用的GetCustomAttributes方法和LINQ使事情变得更整洁。

    /// <summary>
    /// Gets the value of the <see cref="T:System.ComponentModel.DescriptionAttribute"/> on an struct, including enums.  
    /// </summary>
    /// <typeparam name="T">The type of the struct.</typeparam>
    /// <param name="enumerationValue">A value of type <see cref="T:System.Enum"/></param>
    /// <returns>If the struct has a Description attribute, this method returns the description.  Otherwise it just calls ToString() on the struct.</returns>
    /// <remarks>Based on http://stackoverflow.com/questions/479410/enum-tostring/479417#479417, but useful for any struct.</remarks>
    public static string GetDescription<T>(this T enumerationValue) where T : struct
    {
        return enumerationValue.GetType().GetMember(enumerationValue.ToString())
                .SelectMany(mi => mi.GetCustomAttributes<DescriptionAttribute>(false),
                    (mi, ca) => ca.Description)
                .FirstOrDefault() ?? enumerationValue.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

我碰巧是个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#在扩展等新主题上已经生疏了)