我的枚举包含以下值:
private enum PublishStatusses{
NotCompleted,
Completed,
Error
};
我希望能以用户友好的方式输出这些值。
但我不需要再将字符串转换回值。
不要使用枚举,而是使用静态类。
替换
private enum PublishStatuses{
NotCompleted,
Completed,
Error
};
使用
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"
使用“扩展方法”解决方案时出现问题:
私有枚举通常在另一个类内部使用。扩展方法解决方案在此处无效,因为它必须在自己的类中。这个解决方案可以是私有的,并嵌入到另一个类中。
Enums
传递给方法时,将失去其值,因为所有方法签名都需要 string
,因此可以传递任何内容。这会引入需要额外验证并降低通用可读性的需求。 - CajunCodingpublic static string GetDescription<T>(this object enumerationValue)
where T : struct
{
Type type = enumerationValue.GetType();
if (!type.IsEnum)
{
throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
}
//Tries to find a DescriptionAttribute for a potential friendly name
//for the enum
MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
if (memberInfo != null && memberInfo.Length > 0)
{
object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0 && attrs.Where(t => t.GetType() == typeof(DescriptionAttribute)).FirstOrDefault() != null)
{
//Pull out the description value
return ((DescriptionAttribute)attrs.Where(t=>t.GetType() == typeof(DescriptionAttribute)).FirstOrDefault()).Description;
}
}
//If we have no description attribute, just return the ToString of the enum
return enumerationValue.ToString();
以下是建议摘要和示例:
namespace EnumExtensions {
using System;
using System.Reflection;
public class TextAttribute : Attribute {
public string Text;
public TextAttribute( string text ) {
Text = text;
}//ctor
}// class TextAttribute
public static class EnumExtender {
public static string ToText( this Enum enumeration ) {
MemberInfo[] memberInfo = enumeration.GetType().GetMember( enumeration.ToString() );
if ( memberInfo != null && memberInfo.Length > 0 ) {
object[] attributes = memberInfo[ 0 ].GetCustomAttributes( typeof(TextAttribute), false );
if ( attributes != null && attributes.Length > 0 ) {
return ( (TextAttribute)attributes[ 0 ] ).Text;
}
}//if
return enumeration.ToString();
}//ToText
}//class EnumExtender
}//namespace
使用方法:
using System;
using EnumExtensions;
class Program {
public enum Appearance {
[Text( "left-handed" ) ]
Left,
[Text( "right-handed" ) ]
Right,
}//enum
static void Main( string[] args ) {
var appearance = Appearance.Left;
Console.WriteLine( appearance.ToText() );
}//Main
}//class
我晚了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")
我恰巧是VB.NET的粉丝,下面是我的版本,结合了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 ()中,通过Console.WriteLine调用时,最后一个参数是简单的v.Description
。对于V1,返回“One”,对于V2,则返回“V2”,对于V3,则返回“Three”。实际上,这个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
中,该字典在需要时填充。ToString(string)
的内部实现已经避免了装箱并且缓存了结果,所以手动实现已经不再必要,而且可能比内置方法的性能差。 - undefined更加简洁的概述:
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();
}
}
使用 Enum.GetName
从上面的链接中...
using System;
public class GetNameTest {
enum Colors { Red, Green, Blue, Yellow };
enum Styles { Plaid, Striped, Tartan, Corduroy };
public static void Main() {
Console.WriteLine("The 4th value of the Colors Enum is {0}", Enum.GetName(typeof(Colors), 3));
Console.WriteLine("The 4th value of the Styles Enum is {0}", Enum.GetName(typeof(Styles), 3));
}
}
// The example displays the following output:
// The 4th value of the Colors Enum is Yellow
// The 4th value of the Styles Enum is Corduroy
public enum Example
{
Example1,
Example2
}
Console.WriteLine(Example.Example1.ToString("g"));
//Outputs: "Example1"
ToString(IFormatProvider)
方法中的IFormatProvider。最有效的方法往往是使用一个扩展方法,其中包含一个switch表达式,根据枚举值返回字符串,并根据您可能想要添加的其他行为进行扩展。 - undefined// Enum
[Newtonsoft.Json.JsonConverter(typeof(StringEnumConverter))]
public enum MyEnum
{
[EnumMember(Value = "User friendly value")]
SomeValue=0,
}
// Usage as extension method
public static string ToDefaultString(this Enum enumValue)
{
return JsonConvert.SerializeObject(enumValue).Replace("\"", "");
}
这是对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 https://dev59.com/knRB5IYBdhLWcg3w4bEo#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();
}