我有以下列举:

public enum AuthenticationMethod
{FORMS = 1,WINDOWSAUTHENTICATION = 2,SINGLESIGNON = 3
}

但是问题是,当我要求AuthenticationMethod.FORMS而不是ID 1时,我需要单词“ FORMS”。

我已经找到以下针对此问题的解决方案( link ):

首先,我需要创建一个名为“ StringValue”的自定义属性:

public class StringValue : System.Attribute
{private readonly string _value;public StringValue(string value){_value = value;}public string Value{get { return _value; }}}

然后,我可以将此属性添加到我的枚举器中:

public enum AuthenticationMethod
{[StringValue("FORMS")]FORMS = 1,[StringValue("WINDOWS")]WINDOWSAUTHENTICATION = 2,[StringValue("SSO")]SINGLESIGNON = 3
}

当然,我需要一些东西来检索该StringValue:

public static class StringEnum
{public static string GetStringValue(Enum value){string output = null;Type type = value.GetType();//Check first in our cached results...//Look for our 'StringValueAttribute' //in the field's custom attributesFieldInfo fi = type.GetField(value.ToString());StringValue[] attrs =fi.GetCustomAttributes(typeof(StringValue),false) as StringValue[];if (attrs.Length > 0){output = attrs[0].Value;}return output;}
}

好了,现在我有了一些工具来获取枚举器的字符串值。 然后,我可以像这样使用它:

string valueOfAuthenticationMethod = StringEnum.GetStringValue(AuthenticationMethod.FORMS);

好的,现在所有这些工作都像是一种魅力,但我发现它完成了很多工作。 我想知道是否有更好的解决方案。

我也尝试了一些具有字典和静态属性的方法,但这也不是更好。


#1楼

我如何解决此问题作为扩展方法:

using System.ComponentModel;
public static string GetDescription(this Enum value)
{var descriptionAttribute = (DescriptionAttribute)value.GetType().GetField(value.ToString()).GetCustomAttributes(false).Where(a => a is DescriptionAttribute).FirstOrDefault();return descriptionAttribute != null ? descriptionAttribute.Description : value.ToString();
}

枚举:

public enum OrderType
{None = 0,[Description("New Card")]NewCard = 1,[Description("Reload")]Refill = 2
}

用法(其中o.OrderType是与枚举名称相同的属性):

o.OrderType.GetDescription()

这给了我一个字符串“ New Card”或“ Reload”,而不是实际的枚举值“ NewCard and Refill”。


#2楼

只需使用ToString()方法

public enum any{Tomato=0,Melon,Watermelon}

要引用字符串Tomato ,只需使用

any.Tomato.ToString();

#3楼

对我来说,务实的方法是在班级里上课,示例:

public class MSEModel
{class WITS{public const string DATE = "5005";public const string TIME = "5006";public const string MD = "5008";public const string ROP = "5075";public const string WOB = "5073";public const string RPM = "7001";
... }

#4楼

好吧,在阅读了以上所有内容后,我觉得这些家伙将将枚举数转换为字符串的问题变得更加复杂。 我喜欢在枚举字段上具有属性的想法,但是我认为属性主要用于元数据,但是在您的情况下,我认为您所需要的只是某种本地化。

public enum Color
{ Red = 1, Green = 2, Blue = 3}public static EnumUtils
{public static string GetEnumResourceString(object enumValue){Type enumType = enumValue.GetType();string value = Enum.GetName(enumValue.GetType(), enumValue);string resourceKey = String.Format("{0}_{1}", enumType.Name, value);string result = Resources.Enums.ResourceManager.GetString(resourceKey);if (string.IsNullOrEmpty(result)){result = String.Format("{0}", value);}return result;}
}

现在,如果我们尝试调用上述方法,我们可以这样调用它

public void Foo()
{var col = Color.Red;Console.WriteLine (EnumUtils.GetEnumResourceString (col));
}

您需要做的就是创建一个包含所有枚举器值和相应字符串的资源文件

Resource Name          Resource Value
Color_Red              My String Color in Red
Color_Blue             Blueeey
Color_Green            Hulk Color

实际上,这样做的好处是,如果您需要对应用程序进行本地化,这将非常有帮助,因为您要做的就是用新语言创建另一个资源文件! 还有Voe-la!


#5楼

这是完成将字符串与枚举关联的另一种方法:

struct DATABASE {public enum enums {NOTCONNECTED, CONNECTED, ERROR}static List<string> strings =new List<string>() {"Not Connected", "Connected", "Error"};public string GetString(DATABASE.enums value) {return strings[(int)value];}
}

此方法的调用方式如下:

public FormMain() {DATABASE dbEnum;string enumName = dbEnum.GetString(DATABASE.enums.NOTCONNECTED);
}

您可以将相关枚举归为一组。 由于此方法使用枚举类型,因此在调用GetString()时可以使用Intellisense显示枚举列表。

您可以选择在DATABASE结构上使用new运算符。 不使用它意味着在第一次调用GetString()之前不会分配字符串List


#6楼

如果您考虑我们要解决的问题,那么这根本不是我们需要的枚举。 我们需要一个允许一定数量的值相互关联的对象。 换句话说,定义一个类。

我在这里看到JakubŠturc的类型安全的枚举模式是最好的选择。

看它:

  • 它具有私有构造函数,因此只有类本身才能定义允许的值。
  • 这是一个密封的类,因此无法通过继承修改值。
  • 它是类型安全的,允许您的方法仅要求该类型。
  • 访问这些值不会导致反射性能下降。
  • 最后,可以对其进行修改以将两个以上的字段关联在一起,例如,名称,说明和数字值。

#7楼

我真的很喜欢JakubŠturc的回答,但是缺点是您不能在switch-case语句中使用它。 这是他的答案的略微修改版本,可以与switch语句一起使用:

public sealed class AuthenticationMethod
{#region This code never needs to change.private readonly string _name;public readonly Values Value;private AuthenticationMethod(Values value, String name){this._name = name;this.Value = value;}public override String ToString(){return _name;}#endregionpublic enum Values{Forms = 1,Windows = 2,SSN = 3}public static readonly AuthenticationMethod FORMS = new AuthenticationMethod (Values.Forms, "FORMS");public static readonly AuthenticationMethod WINDOWSAUTHENTICATION = new AuthenticationMethod (Values.Windows, "WINDOWS");public static readonly AuthenticationMethod SINGLESIGNON = new AuthenticationMethod (Values.SSN, "SSN");
}

因此,您可以获得JakubŠturc答案的所有好处,而且我们可以将其与switch语句一起使用,如下所示:

var authenticationMethodVariable = AuthenticationMethod.FORMS;  // Set the "enum" value we want to use.
var methodName = authenticationMethodVariable.ToString();       // Get the user-friendly "name" of the "enum" value.// Perform logic based on which "enum" value was chosen.
switch (authenticationMethodVariable.Value)
{case authenticationMethodVariable.Values.Forms: // Do somethingbreak;case authenticationMethodVariable.Values.Windows: // Do somethingbreak;case authenticationMethodVariable.Values.SSN: // Do somethingbreak;
}

#8楼

当我遇到这种情况时,请提出以下解决方案。

作为消费阶层,您可以

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace MyApp.Dictionaries
{class Greek{public static readonly string Alpha = "Alpha";public static readonly string Beta = "Beta";public static readonly string Gamma = "Gamma";public static readonly string Delta = "Delta";private static readonly BiDictionary<int, string> Dictionary = new BiDictionary<int, string>();static Greek() {Dictionary.Add(1, Alpha);Dictionary.Add(2, Beta);Dictionary.Add(3, Gamma);Dictionary.Add(4, Delta);}public static string getById(int id){return Dictionary.GetByFirst(id);}public static int getByValue(string value){return Dictionary.GetBySecond(value);}}
}

并使用双向字典:基于此( https://stackoverflow.com/a/255638/986160 ),假定键将与字典中的单个值相关联,并且类似于( https://stackoverflow.com/a / 255630/986160 ),但更加优雅。 该字典也是可枚举的,您可以从整数到字符串来回切换。 另外,除了此类之外,您的代码库中也不必包含任何字符串。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;namespace MyApp.Dictionaries
{class BiDictionary<TFirst, TSecond> : IEnumerable{IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();public void Add(TFirst first, TSecond second){firstToSecond.Add(first, second);secondToFirst.Add(second, first);}public TSecond this[TFirst first]{get { return GetByFirst(first); }}public TFirst this[TSecond second]{get { return GetBySecond(second); }}public TSecond GetByFirst(TFirst first){return firstToSecond[first];}public TFirst GetBySecond(TSecond second){return secondToFirst[second];}public IEnumerator GetEnumerator(){return GetFirstEnumerator();}public IEnumerator GetFirstEnumerator(){return firstToSecond.GetEnumerator();}public IEnumerator GetSecondEnumerator(){return secondToFirst.GetEnumerator();}}
}

#9楼

这里有很多很好的答案,但就我而言,这并不能解决我从“字符串枚举”中想要的东西:

  1. 在switch语句中可用,例如switch(myEnum)
  2. 可以在函数参数中使用,例如foo(myEnum type)
  3. 可以引用例如myEnum.FirstElement
  4. 我可以使用字符串,例如foo(“ FirstElement”)== foo(myEnum.FirstElement)

1,2和4实际上可以使用字符串的C#Typedef解决(因为字符串可以在c#中切换)

3可以通过静态const字符串解决。 因此,如果您有相同的需求,这是最简单的方法:

public sealed class Types
{private readonly String name;private Types(String name){this.name = name;}public override String ToString(){return name;}public static implicit operator Types(string str){return new Types(str);}public static implicit operator string(Types str){return str.ToString();}#region enumpublic const string DataType = "Data";public const string ImageType = "Image";public const string Folder = "Folder";#endregion}

例如,这允许:

    public TypeArgs(Types SelectedType){Types SelectedType = SelectedType}

public TypeObject CreateType(Types type){switch (type){case Types.ImageType://break;case Types.DataType://break;}}

可以使用字符串或类型调用CreateType的地方。 但是不利的是,任何字符串自动都是有效的枚举 ,可以对其进行修改,但是随后它将需要某种init函数...或者可能使它们显式转换为内部变量?

现在,如果一个int值是你(也许比对速度)重要的是,你可以使用来自的JakubŠturc梦幻般的答案的一些想法,做一些事情有点疯狂,这是我的刺吧:

    public sealed class Types
{private static readonly Dictionary<string, Types> strInstance = new Dictionary<string, Types>();private static readonly Dictionary<int, Types> intInstance = new Dictionary<int, Types>();private readonly String name;private static int layerTypeCount = 0;private int value;private Types(String name){this.name = name;value = layerTypeCount++;strInstance[name] = this;intInstance[value] = this;}public override String ToString(){return name;}public static implicit operator Types(int val){Types result;if (intInstance.TryGetValue(val, out result))return result;elsethrow new InvalidCastException();}public static implicit operator Types(string str){Types result;if (strInstance.TryGetValue(str, out result)){return result;}else{result = new Types(str);return result;}}public static implicit operator string(Types str){return str.ToString();}public static bool operator ==(Types a, Types b){return a.value == b.value;}public static bool operator !=(Types a, Types b){return a.value != b.value;}#region enumpublic const string DataType = "Data";public const string ImageType = "Image";#endregion}

但当然是“ Types bob = 4;” 除非您先对其进行了初始化,否则将毫无意义……

但是理论上TypeA == TypeB会更快...


#10楼

在您的问题中,您从未说过您实际上在任何地方都需要枚举的数值。

如果不这样做,只需要一个字符串类型的枚举(它不是整数类型,那么就不能成为枚举的基础),这是一种方法:

    static class AuthenticationMethod{public static readonly stringFORMS = "Forms",WINDOWSAUTHENTICATION = "WindowsAuthentication";}

您可以使用与枚举相同的语法来引用它

if (bla == AuthenticationMethod.FORMS)

这将比使用数字值(比较字符串而不是数字)要慢一些,但从正面看,它没有使用反射(慢速)来访问字符串。


#11楼

基于MSDN的网站: http : //msdn.microsoft.com/en-us/library/cc138362.aspx

foreach (string str in Enum.GetNames(typeof(enumHeaderField)))
{Debug.WriteLine(str);
}

str将是字段的名称


#12楼

.Net 4.0及更高版本对此非常简单的解决方案。 不需要其他代码。

public enum MyStatus
{Active = 1,Archived = 2
}

要获取有关字符串的信息,请使用:

MyStatus.Active.ToString("f");

要么

MyStatus.Archived.ToString("f");`

该值将为“有效”或“已归档”。

要在调用Enum.ToString查看不同的字符串格式(上面的“ f”), Enum.ToString见此Enumeration Format Strings页面


#13楼

如果我对您的理解正确,则可以简单地使用.ToString()从值中检索枚举的名称(假设它已被强制转换为Enum); 如果您有裸露的int(可以说是从数据库之类的东西),则可以先将其转换为枚举。 以下两种方法都会为您提供枚举名称。

AuthenticationMethod myCurrentSetting = AuthenticationMethod.FORMS;
Console.WriteLine(myCurrentSetting); // Prints: FORMS
string name = Enum.GetNames(typeof(AuthenticationMethod))[(int)myCurrentSetting-1];
Console.WriteLine(name); // Prints: FORMS

但是请记住,第二种方法假定您使用的是int且索引基于1(而不是基于0)。 通过比较,GetNames函数也很繁琐,每次调用时都会生成一个整个数组。 如您在第一种技术中所看到的,.ToString()实际上是隐式调用的。 当然,答案中都已经提到了这两种方法,我只是想澄清它们之间的区别。


#14楼

旧帖子但是...

答案实际上可能非常简单。 使用Enum.ToString()函数

此函数有6个重载,可以使用Enum.Tostring(“ F”)或Enum.ToString()返回字符串值。 无需理会其他任何事情。 这是一个正在工作的演示

请注意,该解决方案可能不适用于所有编译器( 此演示无法按预期工作 ),但至少它适用于最新的编译器。


#15楼

使用方法

Enum.GetName(Type MyEnumType,  object enumvariable)

如(假设Shipper是已定义的枚举)

Shipper x = Shipper.FederalExpress;
string s = Enum.GetName(typeof(Shipper), x);

Enum类上还有许多其他静态方法也值得研究...


#16楼

不幸的是,在枚举中获取属性的反思非常缓慢:

看到这个问题: 有人知道一种快速获取枚举值的自定义属性的方法吗?

.ToString()在枚举上也很慢。

不过,您可以为枚举编写扩展方法:

public static string GetName( this MyEnum input ) {switch ( input ) {case MyEnum.WINDOWSAUTHENTICATION:return "Windows";//and so on}
}

这不是很好,但是会很快并且不需要反射属性或字段名称。


C#6更新

如果可以使用C#6,则新的nameof运算符适用于枚举,因此nameof(MyEnum.WINDOWSAUTHENTICATION)将在编译时转换为"WINDOWSAUTHENTICATION" ,这是获取枚举名称的最快方法。

请注意,这会将显式枚举转换为内联常量,因此不适用于变量中包含的枚举。 所以:

nameof(AuthenticationMethod.FORMS) == "FORMS"

但...

var myMethod = AuthenticationMethod.FORMS;
nameof(myMethod) == "myMethod"

#17楼

您可以使用ToString()引用名称而不是值

Console.WriteLine("Auth method: {0}", AuthenticationMethod.Forms.ToString());

文档在这里:

http://msdn.microsoft.com/zh-CN/library/16c1xs4z.aspx

...并且如果您在Pascal Case中命名枚举(例如,我这样做-例如ThisIsMyEnumValue = 1等),则可以使用非常简单的正则表达式来打印友好形式:

static string ToFriendlyCase(this string EnumString)
{return Regex.Replace(EnumString, "(?!^)([A-Z])", " $1");
}

可以很容易地从任何字符串中调用它:

Console.WriteLine("ConvertMyCrazyPascalCaseSentenceToFriendlyCase".ToFriendlyCase());

输出:

将我疯狂的Pascal案例句子转换为友好案例

这样可以省去创建自定义属性并将其附加到枚举的麻烦,也可以使用查找表将枚举值与友好的字符串结合使用,并且最重要的是它可以自我管理,并且可以在任何无穷大的Pascal Case字符串上使用更可重用。 当然,它不允许您使用与解决方案提供的枚举不同的友好名称。

不过,对于更复杂的情况,我确实喜欢您的原始解决方案。 您可以将解决方案更进一步,使GetStringValue成为枚举的扩展方法,然后就不需要像StringEnum.GetStringValue一样引用它了。

public static string GetStringValue(this AuthenticationMethod value)
{string output = null;Type type = value.GetType();FieldInfo fi = type.GetField(value.ToString());StringValue[] attrs = fi.GetCustomAttributes(typeof(StringValue), false) as StringValue[];if (attrs.Length > 0)output = attrs[0].Value;return output;
}

然后,您可以直接从枚举实例轻松访问它:

Console.WriteLine(AuthenticationMethod.SSO.GetStringValue());

#18楼

尝试使用类型安全的枚举模式。

public sealed class AuthenticationMethod {private readonly String name;private readonly int value;public static readonly AuthenticationMethod FORMS = new AuthenticationMethod (1, "FORMS");public static readonly AuthenticationMethod WINDOWSAUTHENTICATION = new AuthenticationMethod (2, "WINDOWS");public static readonly AuthenticationMethod SINGLESIGNON = new AuthenticationMethod (3, "SSN");        private AuthenticationMethod(int value, String name){this.name = name;this.value = value;}public override String ToString(){return name;}}

更新显式(或隐式)类型转换可以通过

  • 通过映射添加静态字段

     private static readonly Dictionary<string, AuthenticationMethod> instance = new Dictionary<string,AuthenticationMethod>(); 
    • nb为了使“枚举成员”字段的初始化在调用实例构造函数时不会引发NullReferenceException,请确保将Dictionary字段放在类中的“枚举成员”字段之前。 这是因为静态字段初始化程序是按声明顺序调用的,并且是在静态构造函数之前调用的,这造成了一种奇怪且必要的但令人困惑的情况,即可以在初始化所有静态字段之前以及在调用静态构造函数之前调用实例构造函数。
  • 在实例构造函数中填充此映射

     instance[name] = this; 
  • 并添加用户定义的类型转换运算符

     public static explicit operator AuthenticationMethod(string str) { AuthenticationMethod result; if (instance.TryGetValue(str, out result)) return result; else throw new InvalidCastException(); } 

#19楼

我使用System.ComponentModel命名空间中的Description属性。 只需装饰枚举,然后使用以下代码对其进行检索:

public 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 enumMemberInfo[] 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){//Pull out the description valuereturn ((DescriptionAttribute)attrs[0]).Description;}}//If we have no description attribute, just return the ToString of the enumreturn enumerationValue.ToString();}

举个例子:

public enum Cycle : int
{        [Description("Daily Cycle")]Daily = 1,Weekly,Monthly
}

此代码很好地迎合了不需要“友好名称”的枚举,并且仅返回枚举的.ToString()。


#20楼

我同意基思(Keith)的观点,但我无法投票(尚未)。

我使用静态方法和swith语句来完全返回我想要的。 在数据库中,我存储了tinyint,而我的代码仅使用实际的枚举,因此这些字符串用于UI要求。 经过大量测试,这导致了最佳性能和对输出的最大控制。

public static string ToSimpleString(this enum)
{switch (enum){case ComplexForms:return "ComplexForms";break;}
}public static string ToFormattedString(this enum)
{switch (enum){case ComplexForms:return "Complex Forms";break;}
}

但是,由于某些原因,这可能导致维护方面的噩梦和某些代码异味。 我试图留意那些枚举长,枚举很多或经常更改的枚举。 否则,这对我来说是一个很好的解决方案。


#21楼

选项1:

public sealed class FormsAuth
{public override string ToString{return "Forms Authtentication";}
}
public sealed class WindowsAuth
{public override string ToString{return "Windows Authtentication";}
}public sealed class SsoAuth
{public override string ToString{return "SSO";}
}

接着

object auth = new SsoAuth(); //or whatever//...
//...
// blablablaDoSomethingWithTheAuth(auth.ToString());

选项2:

public enum AuthenticationMethod
{FORMS = 1,WINDOWSAUTHENTICATION = 2,SINGLESIGNON = 3
}public class MyClass
{private Dictionary<AuthenticationMethod, String> map = new Dictionary<AuthenticationMethod, String>();public MyClass(){map.Add(AuthenticationMethod.FORMS,"Forms Authentication");map.Add(AuthenticationMethod.WINDOWSAUTHENTICATION ,"Windows Authentication");map.Add(AuthenticationMethod.SINGLESIGNON ,"SSo Authentication");}
}

#22楼

我结合了上面的一些建议和一些缓存。 现在,我从网上找到的一些代码中得到了这个主意,但是我不记得在哪里找到它或在哪里找到它。 因此,如果有人找到相似的内容,请注明出处。

无论如何,用法都涉及类型转换器,因此,如果您绑定到UI,它将“起作用”。 通过将类型转换器初始化为静态方法,可以使用Jakub的模式进行扩展以快速查找代码。

基本用法如下所示

[TypeConverter(typeof(CustomEnumTypeConverter<MyEnum>))]
public enum MyEnum
{// The custom type converter will use the description attribute[Description("A custom description")]ValueWithCustomDescription,// This will be exposed exactly.Exact
}

自定义枚举类型转换器的代码如下:

public class CustomEnumTypeConverter<T> : EnumConverterwhere T : struct
{private static readonly Dictionary<T,string> s_toString = new Dictionary<T, string>();private static readonly Dictionary<string, T> s_toValue = new Dictionary<string, T>();private static bool s_isInitialized;static CustomEnumTypeConverter(){System.Diagnostics.Debug.Assert(typeof(T).IsEnum,"The custom enum class must be used with an enum type.");}public CustomEnumTypeConverter() : base(typeof(T)){if (!s_isInitialized){Initialize();s_isInitialized = true;}}protected void Initialize(){foreach (T item in Enum.GetValues(typeof(T))){string description = GetDescription(item);s_toString[item] = description;s_toValue[description] = item;}}private static string GetDescription(T optionValue){var optionDescription = optionValue.ToString();var optionInfo = typeof(T).GetField(optionDescription);if (Attribute.IsDefined(optionInfo, typeof(DescriptionAttribute))){var attribute = (DescriptionAttribute)Attribute.GetCustomAttribute(optionInfo, typeof(DescriptionAttribute));return attribute.Description;}return optionDescription;}public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType){var optionValue = (T)value;if (destinationType == typeof(string) && s_toString.ContainsKey(optionValue)){return s_toString[optionValue];}return base.ConvertTo(context, culture, value, destinationType);}public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value){var stringValue = value as string;if (!string.IsNullOrEmpty(stringValue) && s_toValue.ContainsKey(stringValue)){return s_toValue[stringValue];}return base.ConvertFrom(context, culture, value);}
}

}


#23楼

当我遇到这个问题时,有几个问题我想首先找到答案:

  • 我的枚举值的名称是否足够友好用于此目的,或者我需要提供更友好的名称?
  • 我需要往返吗? 也就是说,我是否需要获取文本值并将其解析为枚举值?
  • 这是我需要为项目中的多个枚举(还是仅一个枚举)执行的操作?
  • 我将使用哪种UI元素来呈现此信息-特别是将其绑定到UI还是使用属性表?
  • 这需要本地化吗?

最简单的方法是使用Enum.GetValue (并使用Enum.Parse支持往返)。 正如Steve Mitcham所建议的那样,通常还值得构建一个TypeConverter来支持UI绑定。 (使用属性表时不必构建TypeConverter ,这是关于属性表的优点之一。尽管上帝知道它们有其自身的问题。)

通常,如果对上述问题的回答表明这行不通,那么下一步就是创建并填充静态Dictionary<MyEnum, string>或可能的Dictionary<Type, Dictionary<int, string>> 。 我倾向于跳过中间的“用属性修饰代码”步骤,因为下一步通常是在部署后需要更改友好值(通常但由于本地化而并非总是如此)。


#24楼

我想将其发布为对下面引用的帖子的评论,但是由于我没有足够的代表而无法发布-因此请不要投票。 代码中包含错误,我想向尝试使用此解决方案的个人指出:

 [TypeConverter(typeof(CustomEnumTypeConverter(typeof(MyEnum))] public enum MyEnum { // The custom type converter will use the description attribute [Description("A custom description")] ValueWithCustomDescription, // This will be exposed exactly. Exact } 

应该

[TypeConverter(typeof(CustomEnumTypeConverter<MyEnum>))]
public enum MyEnum
{// The custom type converter will use the description attribute[Description("A custom description")]ValueWithCustomDescription,// This will be exposed exactly.Exact
}

太棒了!


#25楼

对于较大的字符串枚举集,列出的示例可能会令人厌烦。 如果需要状态代码列表或其他基于字符串的枚举列表,则使用属性系统很烦人,而带有自身实例的静态类则很烦人。 对于我自己的解决方案,我使用T4模板来简化具有字符串支持的枚举的过程。 结果类似于HttpMethod类的工作原理。

您可以像这样使用它:

    string statusCode = ResponseStatusCode.SUCCESS; // Automatically converts to string when neededResponseStatusCode codeByValueOf = ResponseStatusCode.ValueOf(statusCode); // Returns null if not found// Implements TypeConverter so you can use it with string conversion methods.var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(ResponseStatusCode));ResponseStatusCode code = (ResponseStatusCode) converter.ConvertFromInvariantString(statusCode);// You can get a full list of the valuesbool canIterateOverValues = ResponseStatusCode.Values.Any(); // Comparisons are by value of the "Name" property. Not by memory pointer location.bool implementsByValueEqualsEqualsOperator = "SUCCESS" == ResponseStatusCode.SUCCESS;

您从一个Enum.tt文件开始。

<#@ include file="StringEnum.ttinclude" #><#+
public static class Configuration
{public static readonly string Namespace = "YourName.Space";public static readonly string EnumName = "ResponseStatusCode";public static readonly bool IncludeComments = true;public static readonly object Nodes = new{SUCCESS = "The response was successful.",NON_SUCCESS = "The request was not successful.",RESOURCE_IS_DISCONTINUED = "The resource requested has been discontinued and can no longer be accessed."};
}
#>

然后,添加您的StringEnum.ttinclude文件。

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
<#@ CleanupBehavior processor="T4VSHost" CleanupAfterProcessingtemplate="true" #>//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;namespace <#= Configuration.Namespace #>
{/// <summary>/// TypeConverter implementations allow you to use features like string.ToNullable(T)./// </summary>public class <#= Configuration.EnumName #>TypeConverter : TypeConverter{public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType){return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);}public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value){var casted = value as string;if (casted != null){var result = <#= Configuration.EnumName #>.ValueOf(casted);if (result != null){return result;}}return base.ConvertFrom(context, culture, value);}public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType){var casted = value as <#= Configuration.EnumName #>;if (casted != null && destinationType == typeof(string)){return casted.ToString();}return base.ConvertTo(context, culture, value, destinationType);}}[TypeConverter(typeof(<#= Configuration.EnumName #>TypeConverter))]public class <#= Configuration.EnumName #> : IEquatable<<#= Configuration.EnumName #>>{
//---------------------------------------------------------------------------------------------------
// V A L U E S _ L I S T
//---------------------------------------------------------------------------------------------------
<# Write(Helpers.PrintEnumProperties(Configuration.Nodes)); #>private static List<<#= Configuration.EnumName #>> _list { get; set; } = null;public static List<<#= Configuration.EnumName #>> ToList(){if (_list == null){_list = typeof(<#= Configuration.EnumName #>).GetFields().Where(x => x.IsStatic && x.IsPublic && x.FieldType == typeof(<#= Configuration.EnumName #>)).Select(x => x.GetValue(null)).OfType<<#= Configuration.EnumName #>>().ToList();}return _list;}public static List<<#= Configuration.EnumName #>> Values(){return ToList();}/// <summary>/// Returns the enum value based on the matching Name of the enum. Case-insensitive search./// </summary>/// <param name="key"></param>/// <returns></returns>public static <#= Configuration.EnumName #> ValueOf(string key){return ToList().FirstOrDefault(x => string.Compare(x.Name, key, true) == 0);}//---------------------------------------------------------------------------------------------------
// I N S T A N C E _ D E F I N I T I O N
//---------------------------------------------------------------------------------------------------      public string Name { get; private set; }public string Description { get; private set; }public override string ToString() { return this.Name; }/// <summary>/// Implcitly converts to string./// </summary>/// <param name="d"></param>public static implicit operator string(<#= Configuration.EnumName #> d){return d.ToString();}/// <summary>/// Compares based on the == method. Handles nulls gracefully./// </summary>/// <param name="a"></param>/// <param name="b"></param>/// <returns></returns>public static bool operator !=(<#= Configuration.EnumName #> a, <#= Configuration.EnumName #> b){return !(a == b);}/// <summary>/// Compares based on the .Equals method. Handles nulls gracefully./// </summary>/// <param name="a"></param>/// <param name="b"></param>/// <returns></returns>public static bool operator ==(<#= Configuration.EnumName #> a, <#= Configuration.EnumName #> b){return a?.ToString() == b?.ToString();}/// <summary>/// Compares based on the .ToString() method/// </summary>/// <param name="o"></param>/// <returns></returns>public override bool Equals(object o){return this.ToString() == o?.ToString();}/// <summary>/// Compares based on the .ToString() method/// </summary>/// <param name="other"></param>/// <returns></returns>public bool Equals(<#= Configuration.EnumName #> other){return this.ToString() == other?.ToString();}/// <summary>/// Compares based on the .Name property/// </summary>/// <returns></returns>public override int GetHashCode(){return this.Name.GetHashCode();}}
}<#+public static class Helpers
{public static string PrintEnumProperties(object nodes){string o = "";Type nodesTp = Configuration.Nodes.GetType();PropertyInfo[] props = nodesTp.GetProperties().OrderBy(p => p.Name).ToArray();for(int i = 0; i < props.Length; i++){var prop = props[i];if (Configuration.IncludeComments){o += "\r\n\r\n";o += "\r\n        ///<summary>";o += "\r\n        /// "+Helpers.PrintPropertyValue(prop, Configuration.Nodes);o += "\r\n        ///</summary>";}o += "\r\n        public static readonly "+Configuration.EnumName+" "+prop.Name+ " = new "+Configuration.EnumName+"(){ Name = \""+prop.Name+"\", Description = "+Helpers.PrintPropertyValue(prop, Configuration.Nodes)+ "};";}o += "\r\n\r\n";return o;}private static Dictionary<string, string> GetValuesMap(){Type nodesTp = Configuration.Nodes.GetType();PropertyInfo[] props= nodesTp.GetProperties();var dic = new Dictionary<string,string>();for(int i = 0; i < props.Length; i++){var prop = nodesTp.GetProperties()[i];dic[prop.Name] = prop.GetValue(Configuration.Nodes).ToString();}return dic;}public static string PrintMasterValuesMap(object nodes){Type nodesTp = Configuration.Nodes.GetType();PropertyInfo[] props= nodesTp.GetProperties();string o = "        private static readonly Dictionary<string, string> ValuesMap = new Dictionary<string, string>()\r\n        {";for(int i = 0; i < props.Length; i++){var prop = nodesTp.GetProperties()[i];o += "\r\n            { \""+prop.Name+"\", "+(Helpers.PrintPropertyValue(prop,Configuration.Nodes)+" },");}o += ("\r\n        };\r\n");return o;}public static string PrintPropertyValue(PropertyInfo prop, object objInstance){switch(prop.PropertyType.ToString()){case "System.Double":return prop.GetValue(objInstance).ToString()+"D";case "System.Float":return prop.GetValue(objInstance).ToString()+"F";case "System.Decimal":return prop.GetValue(objInstance).ToString()+"M";case "System.Long":return prop.GetValue(objInstance).ToString()+"L";case "System.Boolean":case "System.Int16":case "System.Int32":return prop.GetValue(objInstance).ToString().ToLowerInvariant();case "System.String":return "\""+prop.GetValue(objInstance)+"\"";}return prop.GetValue(objInstance).ToString();}public static string _ (int numSpaces){string o = "";for(int i = 0; i < numSpaces; i++){o += " ";}return o;}
}
#>

最后,重新编译Enum.tt文件,输出如下所示:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------using System;
using System.Linq;
using System.Collections.Generic;namespace YourName.Space
{public class ResponseStatusCode{
//---------------------------------------------------------------------------------------------------
// V A L U E S _ L I S T
//---------------------------------------------------------------------------------------------------///<summary>/// "The response was successful."///</summary>public static readonly ResponseStatusCode SUCCESS = new ResponseStatusCode(){ Name = "SUCCESS", Description = "The response was successful."};///<summary>/// "The request was not successful."///</summary>public static readonly ResponseStatusCode NON_SUCCESS = new ResponseStatusCode(){ Name = "NON_SUCCESS", Description = "The request was not successful."};///<summary>/// "The resource requested has been discontinued and can no longer be accessed."///</summary>public static readonly ResponseStatusCode RESOURCE_IS_DISCONTINUED = new ResponseStatusCode(){ Name = "RESOURCE_IS_DISCONTINUED", Description = "The resource requested has been discontinued and can no longer be accessed."};private static List<ResponseStatusCode> _list { get; set; } = null;public static List<ResponseStatusCode> ToList(){if (_list == null){_list = typeof(ResponseStatusCode).GetFields().Where(x => x.IsStatic && x.IsPublic && x.FieldType == typeof(ResponseStatusCode)).Select(x => x.GetValue(null)).OfType<ResponseStatusCode>().ToList();}return _list;}public static List<ResponseStatusCode> Values(){return ToList();}/// <summary>/// Returns the enum value based on the matching Name of the enum. Case-insensitive search./// </summary>/// <param name="key"></param>/// <returns></returns>public static ResponseStatusCode ValueOf(string key){return ToList().FirstOrDefault(x => string.Compare(x.Name, key, true) == 0);}//---------------------------------------------------------------------------------------------------
// I N S T A N C E _ D E F I N I T I O N
//---------------------------------------------------------------------------------------------------       public string Name { get; set; }public string Description { get; set; }public override string ToString() { return this.Name; }/// <summary>/// Implcitly converts to string./// </summary>/// <param name="d"></param>public static implicit operator string(ResponseStatusCode d){return d.ToString();}/// <summary>/// Compares based on the == method. Handles nulls gracefully./// </summary>/// <param name="a"></param>/// <param name="b"></param>/// <returns></returns>public static bool operator !=(ResponseStatusCode a, ResponseStatusCode b){return !(a == b);}/// <summary>/// Compares based on the .Equals method. Handles nulls gracefully./// </summary>/// <param name="a"></param>/// <param name="b"></param>/// <returns></returns>public static bool operator ==(ResponseStatusCode a, ResponseStatusCode b){return a?.ToString() == b?.ToString();}/// <summary>/// Compares based on the .ToString() method/// </summary>/// <param name="o"></param>/// <returns></returns>public override bool Equals(object o){return this.ToString() == o?.ToString();}/// <summary>/// Compares based on the .Name property/// </summary>/// <returns></returns>public override int GetHashCode(){return this.Name.GetHashCode();}}
}

#26楼

Enum.GetName(typeof(MyEnum), (int)MyEnum.FORMS)
Enum.GetName(typeof(MyEnum), (int)MyEnum.WINDOWSAUTHENTICATION)
Enum.GetName(typeof(MyEnum), (int)MyEnum.SINGLESIGNON)

输出为:

“形式”

“ WINDOWSAUTHENTICATION”

“ SINGLESIGNON”


#27楼

使用对象Enum.Parse(System.Type enumType,string value,bool ignoreCase); 从http://blogs.msdn.com/b/tims/archive/2004/04/02/106310.aspx获得


#28楼

更新: 8年后,在长时间不接触C#之后访问此页面,看来我的答案不再是最好的解决方案。 我真的很喜欢与属性函数绑定的转换器解决方案。

如果您正在阅读本文,请确保您还查看其他答案。
(提示:它们高于此值)


像你们大多数人一样,我真的很喜欢JakubŠturc所选择的答案 ,但我也非常讨厌复制粘贴代码,并尽我所能去做。

因此,我决定我想要一个EnumBase类,从该类继承/内置了大多数功能,让我专注于内容而不是行为。

这种方法的主要问题基于以下事实:尽管Enum值是类型安全的实例,但交互作用是与Enum Class类型的Static实现。 因此,在一点泛型魔术的帮助下,我认为我终于有了正确的搭配。 希望有人能像我一样有用。

我将从Jakub的示例开始,但使用继承和泛型:

public sealed class AuthenticationMethod : EnumBase<AuthenticationMethod, int>
{public static readonly AuthenticationMethod FORMS =new AuthenticationMethod(1, "FORMS");public static readonly AuthenticationMethod WINDOWSAUTHENTICATION =new AuthenticationMethod(2, "WINDOWS");public static readonly AuthenticationMethod SINGLESIGNON =new AuthenticationMethod(3, "SSN");private AuthenticationMethod(int Value, String Name): base( Value, Name ) { }public new static IEnumerable<AuthenticationMethod> All{ get { return EnumBase<AuthenticationMethod, int>.All; } }public static explicit operator AuthenticationMethod(string str){ return Parse(str); }
}

这是基类:

using System;
using System.Collections.Generic;
using System.Linq; // for the .AsEnumerable() method call// E is the derived type-safe-enum class
// - this allows all static members to be truly unique to the specific
//   derived class
public class EnumBase<E, T> where E: EnumBase<E, T>
{#region Instance codepublic T Value { get; private set; }public string Name { get; private set; }protected EnumBase(T EnumValue, string Name){Value = EnumValue;this.Name = Name;mapping.Add(Name, this);}public override string ToString() { return Name; }#endregion#region Static toolsstatic private readonly Dictionary<string, EnumBase<E, T>> mapping;static EnumBase() { mapping = new Dictionary<string, EnumBase<E, T>>(); }protected static E Parse(string name){EnumBase<E, T> result;if (mapping.TryGetValue(name, out result)){return (E)result;}throw new InvalidCastException();}// This is protected to force the child class to expose it's own static// method.// By recreating this static method at the derived class, static// initialization will be explicit, promising the mapping dictionary// will never be empty when this method is called.protected static IEnumerable<E> All{ get { return mapping.Values.AsEnumerable().Cast<E>(); } }#endregion
}

#29楼

我的变体

public struct Colors
{private String current;private static string red = "#ff0000";private static string green = "#00ff00";private static string blue = "#0000ff";private static IList<String> possibleColors; public static Colors Red { get { return (Colors) red; } }public static Colors Green { get { return (Colors) green; } }public static Colors Blue { get { return (Colors) blue; } }static Colors(){possibleColors = new List<string>() {red, green, blue};}public static explicit operator String(Colors value){return value.current;}public static explicit operator Colors(String value){if (!possibleColors.Contains(value)){throw new InvalidCastException();}Colors color = new Colors();color.current = value;return color;}public static bool operator ==(Colors left, Colors right){return left.current == right.current;}public static bool operator !=(Colors left, Colors right){return left.current != right.current;}public bool Equals(Colors other){return Equals(other.current, current);}public override bool Equals(object obj){if (ReferenceEquals(null, obj)) return false;if (obj.GetType() != typeof(Colors)) return false;return Equals((Colors)obj);}public override int GetHashCode(){return (current != null ? current.GetHashCode() : 0);}public override string ToString(){return current;}
}

代码看起来有些丑陋,但是此结构的用法非常具有代表性。

Colors color1 = Colors.Red;
Console.WriteLine(color1); // #ff0000Colors color2 = (Colors) "#00ff00";
Console.WriteLine(color2); // #00ff00// Colors color3 = "#0000ff"; // Compilation error
// String color4 = Colors.Red; // Compilation errorColors color5 = (Colors)"#ff0000";
Console.WriteLine(color1 == color5); // TrueColors color6 = (Colors)"#00ff00";
Console.WriteLine(color1 == color6); // False

另外,我认为,如果需要大量此类枚举,则可以使用代码生成(例如T4)。


#30楼

我使用扩展方法:

public static class AttributesHelperExtension{public static string ToDescription(this Enum value){var da = (DescriptionAttribute[])(value.GetType().GetField(value.ToString())).GetCustomAttributes(typeof(DescriptionAttribute), false);return da.Length > 0 ? da[0].Description : value.ToString();}
}

现在用以下命令装饰enum

public enum AuthenticationMethod
{[Description("FORMS")]FORMS = 1,[Description("WINDOWSAUTHENTICATION")]WINDOWSAUTHENTICATION = 2,[Description("SINGLESIGNON ")]SINGLESIGNON = 3
}

你打电话时

AuthenticationMethod.FORMS.ToDescription()您将获得"FORMS"


#31楼

如果您来这里是为了实现一个简单的“ Enum”,但其值是字符串而不是ints,这是最简单的解决方案:

    public sealed class MetricValueList{public static readonly string Brand = "A4082457-D467-E111-98DC-0026B9010912";public static readonly string Name = "B5B5E167-D467-E111-98DC-0026B9010912";}

实现方式:

var someStringVariable = MetricValueList.Brand;

枚举的字符串表示形式相关推荐

  1. 不全?MySQL数据类型精讲,定点日期枚举文本字符串,json二进制,空间,选择建议,完整详细可收藏

    文章目录 1. MySQL中的数据类型 2. 整数类型 3. 浮点数类型 4. 定点数类型 5. 位类型:BIT 6. 日期与时间类型 7. 文本字符串类型 8. ENUM类型 9. SET类型 10 ...

  2. 上接稳扎稳打Silverlight(20) - 2.0通信之WebClient, 以字符串的形式上传/下载数据

    2.以字符串的形式和流的形式上传数据 REST.cs(WCF创建的用于演示以字符串的形式和流的形式上传数据的REST服务) using System;  using System.Linq;  usi ...

  3. 枚举的遍历和字符串转枚举,枚举转字符串

    enum   mycity     {     beijing,shanghai     } 枚举的遍历   foreach(   mycity   city   in   enum.getvalue ...

  4. [工具]-C语言中字符串的形式打印16进制数据

    C语言中字符串的形式打印16进制数据. 这样写,输出更直观些 #define PRINT_BUF_MAX (32) #define TAG_STRING_MAX (32) static void pr ...

  5. boost::describe模块实现枚举转字符串的测试程序

    boost::describe模块实现枚举转字符串的测试程序 实现功能 C++实现代码 实现功能 boost::describe模块实现枚举转字符串的测试程序 C++实现代码 #include < ...

  6. 每天一道LeetCode-----以字符串的形式输出二叉树所有从根节点到叶子节点的路径

    Binary Tree Paths 原题链接Binary Tree Paths 将二叉树中所有从根节点到叶子节点的路径以字符串的形式输出出来 直接遍历即可,注意只有左右子节点都是空节点时才叫叶子节点 ...

  7. java tostring格式_如何在Java中使用toString()获得数字的字符串表示形式?

    toString()方法中的一个重要方法对象类,它可用于返回一个对象的字符串或文本表示.对象类的toString()方法返回一个字符串,作为指定对象类的名称,后跟" @ "符号和对 ...

  8. java 枚举转换_Java 枚举与字符串的转换

    原标题:Java 枚举与字符串的转换 (点击上方公众号,可快速关注) 来源:xieyu_zy 链接:blog.csdn.net/xieyuooo/article/details/8483267 文章简 ...

  9. C# 声明枚举、枚举值描述 获取枚举值字符串 根据枚举获取枚举值描述

    一.声明枚举值.枚举值描述 using System.ComponentModel;public enum status {/// <summary>/// 取消/// </summ ...

最新文章

  1. Ubuntu16.0.4+1080ti+ cuda9.1+cudnn7.0.5 安装 及 caffe 测试
  2. 一个在windowsXP启动linux as(grub引导)的简单方法
  3. 基元检测 Primitive Detection
  4. 浏览器设置了打开会显示特定网页为什么还是显示2345_Edge没能取代Chrome成为我的主力浏览器...
  5. lnmp环境配置laravel项目白屏问题
  6. Windows cmd 颜色,字体,color font set up
  7. 中科软java笔试题
  8. 因算法裁定“效率低下”,近150名员工遭解雇
  9. vs code中英文标点符号自动更改
  10. Linux中rps/rfs的原理及实现
  11. ROS中launch文件和参数设置
  12. 医学图像自适应计算图像窗宽窗位技巧
  13. WP模板常用调用函数
  14. javascript中this的工作原理以及注意事项
  15. C#通过账号密码访问共享文件夹/目录
  16. 三子棋游戏(支持多子棋)
  17. python爬取网站源代码+图片
  18. 新手上路有哪些开车技巧 , 很实用!
  19. 臻和科技与依莫纳医疗共同开发mRNA肿瘤疫苗;赛多利斯中国应用与服务中心落地上海张江 | 医药健闻...
  20. 中兴V5S旧手机上搭载小型Linux服务器

热门文章

  1. Android binder学习一:主要概念
  2. CentOS安装之后的系统安全配置
  3. 如何去提高代码代码质量
  4. WPF 播放Flash
  5. 详解JavaScript数组过滤相同元素的5种方法
  6. 网上订餐系统的SQL SERVER 2005数据库连接
  7. 利用Pattern和Mather来禁止特殊字符的输入
  8. CodeForces 521D nice贪心
  9. C# 如何在空间运行时调整控件位置和大小
  10. 教你在 Centos 7 中使用 DenyHosts防止ssh暴力破解(亲测)