我的枚举由以下值组成:
private enum PublishStatusses{
NotCompleted,
Completed,
Error
};
我希望能够以用户友好的方式输出这些值。 我不需要再从字符串到值。
我的枚举由以下值组成:
private enum PublishStatusses{
NotCompleted,
Completed,
Error
};
我希望能够以用户友好的方式输出这些值。 我不需要再从字符串到值。
当前回答
如果你想要完全可定制的东西,试试我的解决方案:
http://www.kevinwilliampang.com/post/Mapping-Enums-To-Strings-and-Strings-to-Enums-in-NET.aspx
基本上,这篇文章概述了如何将Description属性附加到每个枚举,并提供了从枚举映射到描述的通用方法。
其他回答
这里最简单的解决方案是使用自定义扩展方法(至少在。net 3.5中-您可以将其转换为早期框架版本的静态帮助器方法)。
public static string ToCustomString(this PublishStatusses value)
{
switch(value)
{
// Return string depending on value.
}
return null;
}
我在这里假设您希望返回enum值的实际名称以外的内容(您可以通过简单地调用ToString来获得)。
public enum MyEnum
{
[Description("Option One")]
Option_One
}
public static string ToDescriptionString(this Enum This)
{
Type type = This.GetType();
string name = Enum.GetName(type, This);
MemberInfo member = type.GetMembers()
.Where(w => w.Name == name)
.FirstOrDefault();
DescriptionAttribute attribute = member != null
? member.GetCustomAttributes(true)
.Where(w => w.GetType() == typeof(DescriptionAttribute))
.FirstOrDefault() as DescriptionAttribute
: null;
return attribute != null ? attribute.Description : name;
}
更简洁的总结是:
using System;
using System.Reflection;
public class TextAttribute : Attribute
{
public string Text;
public TextAttribute(string text)
{
Text = text;
}
}
public static class EnumExtender
{
public static string ToText(this Enum enumeration)
{
var memberInfo = enumeration.GetType().GetMember(enumeration.ToString());
if (memberInfo.Length <= 0) return enumeration.ToString();
var attributes = memberInfo[0].GetCustomAttributes(typeof(TextAttribute), false);
return attributes.Length > 0 ? ((TextAttribute)attributes[0]).Text : enumeration.ToString();
}
}
用法与下划线所描述的相同。
不要使用枚举,使用静态类。
取代
private enum PublishStatuses{
NotCompleted,
Completed,
Error
};
with
private static class PublishStatuses{
public static readonly string NotCompleted = "Not Completed";
public static readonly string Completed = "Completed";
public static readonly string Error = "Error";
};
它是这样使用的
PublishStatuses.NotCompleted; // "Not Completed"
使用顶级“扩展方法”解决方案的问题:
私有枚举通常在另一个类中使用。扩展方法解决方案在那里无效,因为它必须在它自己的类中。这个解决方案可以是私有的,并嵌入到另一个类中。
我碰巧是个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#在扩展等新主题上已经生疏了)