我有以下枚举:
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 attributes
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;
}
}
现在好了我有了获取枚举器字符串值的工具。 我可以这样使用它:
string valueOfAuthenticationMethod = StringEnum.GetStringValue(AuthenticationMethod.FORMS);
好的,现在所有这些都像魅力一样,但我发现它做了很多工作。我想知道是否有更好的解决方案。
我也尝试过使用字典和静态属性的东西,但这也不是更好。
答案 0 :(得分:850)
尝试type-safe-enum模式。
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>();
在实例构造函数
中填充此映射instance[name] = this;
并添加user-defined type conversion operator
public static explicit operator AuthenticationMethod(string str)
{
AuthenticationMethod result;
if (instance.TryGetValue(str, out result))
return result;
else
throw new InvalidCastException();
}
答案 1 :(得分:222)
使用方法
Enum.GetName(Type MyEnumType, object enumvariable)
如(假设Shipper
是定义的枚举)
Shipper x = Shipper.FederalExpress;
string s = Enum.GetName(typeof(Shipper), x);
Enum类还有很多其他静态方法值得研究......
答案 2 :(得分:77)
您可以使用ToString()
来引用名称而不是值Console.WriteLine("Auth method: {0}", AuthenticationMethod.Forms.ToString());
文档在这里:
http://msdn.microsoft.com/en-us/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());
答案 3 :(得分:66)
不幸的是,在枚举上获取属性的反射非常慢:
请参阅此问题:Anyone know a quick way to get to custom attributes on an enum value?
枚举上.ToString()
也很慢。
您可以为枚举编写扩展方法:
public static string GetName( this MyEnum input ) {
switch ( input ) {
case MyEnum.WINDOWSAUTHENTICATION:
return "Windows";
//and so on
}
}
这不是很好,但会很快,不需要反映属性或字段名称。
C#6更新
如果您可以使用C#6,那么新的nameof
运算符适用于枚举,因此{em}将在编译时转换为nameof(MyEnum.WINDOWSAUTHENTICATION)
,这是获取枚举名称的最快捷方式。
请注意,这会将显式枚举转换为内联常量,因此它不适用于变量中的枚举。所以:
"WINDOWSAUTHENTICATION"
但是...
nameof(AuthenticationMethod.FORMS) == "FORMS"
答案 4 :(得分:57)
我使用扩展方法:
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"
。
答案 5 :(得分:39)
只需使用ToString()
方法
public enum any{Tomato=0,Melon,Watermelon}
要引用字符串Tomato
,只需使用
any.Tomato.ToString();
答案 6 :(得分:27)
我使用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 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)
{
//Pull out the description value
return ((DescriptionAttribute)attrs[0]).Description;
}
}
//If we have no description attribute, just return the ToString of the enum
return enumerationValue.ToString();
}
举个例子:
public enum Cycle : int
{
[Description("Daily Cycle")]
Daily = 1,
Weekly,
Monthly
}
此代码非常适合您不需要“友好名称”的枚举,并且只返回枚举的.ToString()。
答案 7 :(得分:27)
.Net 4.0及更高版本的非常简单的解决方案。不需要其他代码。
public enum MyStatus
{
Active = 1,
Archived = 2
}
获取关于使用的字符串:
MyStatus.Active.ToString("f");
或
MyStatus.Archived.ToString("f");`
价值将是&#34;有效&#34;或者&#34;存档&#34;。
要在调用Enum.ToString
时查看不同的字符串格式(&#34; f&#34;来自上方),请参阅此Enumeration Format Strings页面
答案 8 :(得分:24)
我真的很喜欢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;
}
#endregion
public 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 something
break;
case authenticationMethodVariable.Values.Windows: // Do something
break;
case authenticationMethodVariable.Values.SSN: // Do something
break;
}
答案 9 :(得分:12)
我使用了上面几个建议的组合,并结合了一些缓存。现在,我从网上某处找到的一些代码中得到了这个想法,但我既不记得我在哪里找到它或者找到它。因此,如果有人发现类似的内容,请对归因进行评论。
无论如何,这种用法涉及到类型转换器,所以如果你绑定到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> : EnumConverter
where 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);
}
}
}
答案 10 :(得分:11)
在你的问题中,你从未说过你实际上需要任何地方的枚举数值。
如果你不这样做,只需要一个类型字符串的枚举(这不是一个整数类型,因此不能作为枚举的基础),这是一种方法:
static class AuthenticationMethod
{
public static readonly string
FORMS = "Forms",
WINDOWSAUTHENTICATION = "WindowsAuthentication";
}
您可以使用与枚举相同的语法来引用它
if (bla == AuthenticationMethod.FORMS)
它会比使用数值(比较字符串而不是数字)慢一点,但在正面,它不使用反射(慢)来访问字符串。
答案 11 :(得分:10)
我如何解决这个问题作为扩展方法:
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()
这给了我一串“新卡”或“重新加载”,而不是实际的枚举值NewCard和Refill。
答案 12 :(得分:10)
更新: 8年后访问此页面,在长时间未触及C#之后,看起来我的答案不再是最佳解决方案。我非常喜欢与属性函数绑定的转换器解决方案。
如果您正在阅读此内容,请确保您还查看其他答案。
(提示:他们高于这个)
和大多数人一样,我真的很喜欢选中的answer by Jakub Šturc,但我也非常讨厌复制粘贴代码,尽量少尝试。
所以我决定我想要一个EnumBase类,其中大部分功能都是继承/内置的,让我专注于内容而不是行为。
这种方法的主要问题是基于以下事实:虽然Enum值是类型安全的实例,但是交互是使用Enum类类型的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 code
public 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 tools
static 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
}
答案 13 :(得分:9)
如果您来到这里寻求实现一个简单的“枚举”,但其值是字符串而不是整数,这是最简单的解决方案:
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;
答案 14 :(得分:9)
我同意基思,但我还不能投票。
我使用静态方法和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;
}
}
然而,有些人认为,这会导致可能的维护噩梦和一些代码味道。我试着留意那些很长很多枚举的词汇,或者经常变化的词汇。否则,这对我来说是一个很好的解决方案。
答案 15 :(得分:6)
我想发布此作为对下面引用的帖子的评论,但不能,因为我没有足够的代表 - 所以请不要投票。该代码包含错误,我想向尝试使用此解决方案的个人指出:
[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
}
马斯亮!
答案 16 :(得分:6)
当我遇到这个问题时,有几个问题我试图先找到答案:
执行此操作的最简单方法是使用Enum.GetValue
(并使用Enum.Parse
支持往返)。正如Steve Mitcham建议的那样,建立TypeConverter
通常也值得支持UI绑定。 (当你使用属性表时,没有必要建立一个TypeConverter
,这是属性表的好处之一。虽然上帝知道他们有自己的问题。)
一般来说,如果上述问题的答案表明不起作用,我的下一步就是创建并填充静态Dictionary<MyEnum, string>
,或者可能是Dictionary<Type, Dictionary<int, string>>
。我倾向于跳过中间装饰 - 代码与属性步骤,因为接下来通常会出现在长矛上的是需要在部署后更改友好值(通常,但并非总是如此,因为本地化)。
答案 17 :(得分:4)
我创建了一个用于在.NET中创建字符串值枚举的基类。它只是一个C#文件,您可以将其复制并粘贴到项目中,也可以通过名为StringEnum的NuGet软件包进行安装。 GitHub Repo
<completitionlist>
进行注释,Intellisense将建议该枚举名称。 (适用于C#和VB)
///<completionlist cref="HexColor"/>
class HexColor : StringEnum<HexColor>
{
public static readonly HexColor Blue = Create("#FF0000");
public static readonly HexColor Green = Create("#00FF00");
public static readonly HexColor Red = Create("#000FF");
}
// Static Parse Method
HexColor.Parse("#FF0000") // => HexColor.Red
HexColor.Parse("#ff0000", caseSensitive: false) // => HexColor.Red
HexColor.Parse("invalid") // => throws InvalidOperationException
// Static TryParse method.
HexColor.TryParse("#FF0000") // => HexColor.Red
HexColor.TryParse("#ff0000", caseSensitive: false) // => HexColor.Red
HexColor.TryParse("invalid") // => null
// Parse and TryParse returns the preexistent instances
object.ReferenceEquals(HexColor.Parse("#FF0000"), HexColor.Red) // => true
// Conversion from your `StringEnum` to `string`
string myString1 = HexColor.Red.ToString(); // => "#FF0000"
string myString2 = HexColor.Red; // => "#FF0000" (implicit cast)
.Net Standard 1.0
的{{3}} NuGet软件包,使其在.Net Core
> = 1.0,.Net Framework
> = 4.5,Mono
>上运行= 4.6,等等。 /// <summary>
/// Base class for creating string-valued enums in .NET.<br/>
/// Provides static Parse() and TryParse() methods and implicit cast to string.
/// </summary>
/// <example>
/// <code>
/// class Color : StringEnum <Color>
/// {
/// public static readonly Color Blue = Create("Blue");
/// public static readonly Color Red = Create("Red");
/// public static readonly Color Green = Create("Green");
/// }
/// </code>
/// </example>
/// <typeparam name="T">The string-valued enum type. (i.e. class Color : StringEnum<Color>)</typeparam>
public abstract class StringEnum<T> : IEquatable<T> where T : StringEnum<T>, new()
{
protected string Value;
private static Dictionary<string, T> valueDict = new Dictionary<string, T>();
protected static T Create(string value)
{
if (value == null)
return null; // the null-valued instance is null.
var result = new T() { Value = value };
valueDict.Add(value, result);
return result;
}
public static implicit operator string(StringEnum<T> enumValue) => enumValue.Value;
public override string ToString() => Value;
public static bool operator !=(StringEnum<T> o1, StringEnum<T> o2) => o1?.Value != o2?.Value;
public static bool operator ==(StringEnum<T> o1, StringEnum<T> o2) => o1?.Value == o2?.Value;
public override bool Equals(object other) => this.Value.Equals((other as T)?.Value ?? (other as string));
bool IEquatable<T>.Equals(T other) => this.Value.Equals(other.Value);
public override int GetHashCode() => Value.GetHashCode();
/// <summary>
/// Parse the <paramref name="value"/> specified and returns a valid <typeparamref name="T"/> or else throws InvalidOperationException.
/// </summary>
/// <param name="value">The string value representad by an instance of <typeparamref name="T"/>. Matches by string value, not by the member name.</param>
/// <param name="caseSensitive">If true, the strings must match case and takes O(log n). False allows different case but is little bit slower (O(n))</param>
public static T Parse(string value, bool caseSensitive = true)
{
var result = TryParse(value, caseSensitive);
if (result == null)
throw new InvalidOperationException((value == null ? "null" : $"'{value}'") + $" is not a valid {typeof(T).Name}");
return result;
}
/// <summary>
/// Parse the <paramref name="value"/> specified and returns a valid <typeparamref name="T"/> or else returns null.
/// </summary>
/// <param name="value">The string value representad by an instance of <typeparamref name="T"/>. Matches by string value, not by the member name.</param>
/// <param name="caseSensitive">If true, the strings must match case. False allows different case but is slower: O(n)</param>
public static T TryParse(string value, bool caseSensitive = true)
{
if (value == null) return null;
if (valueDict.Count == 0) System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(T).TypeHandle); // force static fields initialization
if (caseSensitive)
{
if (valueDict.TryGetValue(value, out T item))
return item;
else
return null;
}
else
{
// slower O(n) case insensitive search
return valueDict.FirstOrDefault(f => f.Key.Equals(value, StringComparison.OrdinalIgnoreCase)).Value;
// Why Ordinal? => https://esmithy.net/2007/10/15/why-stringcomparisonordinal-is-usually-the-right-choice/
}
}
}
答案 18 :(得分:4)
我的变种
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); // #ff0000
Colors color2 = (Colors) "#00ff00";
Console.WriteLine(color2); // #00ff00
// Colors color3 = "#0000ff"; // Compilation error
// String color4 = Colors.Red; // Compilation error
Colors color5 = (Colors)"#ff0000";
Console.WriteLine(color1 == color5); // True
Colors color6 = (Colors)"#00ff00";
Console.WriteLine(color1 == color6); // False
另外,我认为,如果需要很多这样的枚举,可能会使用代码生成(例如T4)。
答案 19 :(得分:3)
如果你想到我们试图解决的问题,那根本就不是我们需要的一个问题。我们需要一个允许一定数量的值相互关联的对象;换句话说,定义一个类。
JakubŠturc的类型安全枚举模式是我在这里看到的最佳选择。
看看它:
答案 20 :(得分: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";
...
}
答案 21 :(得分:3)
选项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
//...
//...
// blablabla
DoSomethingWithTheAuth(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 :(得分:2)
这是完成将字符串与枚举相关联的另一种方法:
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()
调用时显示枚举列表。
您可以选择在DATABASE
结构上使用new运算符。不使用它意味着在第一次List
调用之前不会分配字符串GetString()
。
答案 23 :(得分:2)
旧帖子但是......
答案可能实际上非常简单。使用Enum.ToString()功能
此函数有6个重载,您可以使用Enum.Tostring(&#34; F&#34;)或Enum.ToString()来返回字符串值。无需为其他任何事情烦恼。这是working Demo
请注意,此解决方案可能不适用于所有编译器(this demo does not work as expected),但至少它适用于最新的编译器。
答案 24 :(得分:2)
如果我正确理解你,你可以简单地使用.ToString()从值中检索枚举的名称(假设它已经被强制转换为枚举); 如果您有裸体int(比如说从数据库或其他东西),您可以先将其转换为枚举。 下面的两种方法都会为您提供枚举名称。
AuthenticationMethod myCurrentSetting = AuthenticationMethod.FORMS;
Console.WriteLine(myCurrentSetting); // Prints: FORMS
string name = Enum.GetNames(typeof(AuthenticationMethod))[(int)myCurrentSetting-1];
Console.WriteLine(name); // Prints: FORMS
请记住,第二种技术假设您正在使用整数并且您的索引是基于1(不是基于0)。相比之下,GetNames函数也非常繁重,每次调用它时都会生成一个完整的数组。 正如您在第一种技术中所看到的,.ToString()实际上是隐式调用的。 当然,答案中已经提到了这两点,我只想澄清它们之间的差异。
答案 25 :(得分:2)
这里有很多很棒的答案,但在我的情况下并没有解决我想要的“字符串枚举”,这是:
1,2&amp; 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 enum
public 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。 然而缺点是任何字符串都是自动有效的枚举,这可能会被修改但是它需要某种初始函数...或者可能使它们显式内部转换?
现在,如果一个int值对你很重要(也许是为了比较速度),你可以使用来自JakubŠturc的一些想法很棒的回答并做一些 bit 疯狂的事情,这是我的努力:
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;
else
throw 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 enum
public const string DataType = "Data";
public const string ImageType = "Image";
#endregion
}
但当然“类型bob = 4;”除非你先把它们初始化,否则会有点失败,这将毫无意义......
但理论上TypeA == TypeB会更快......
答案 26 :(得分:1)
当我遇到这样的情况时,我提出下面的解决方案。
作为消费类,你可以拥有
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),但更优雅。这个字典也是可枚举的,你可以从int到字符串来回转换。此外,除了此类之外,您不必在代码库中包含任何字符串。
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();
}
}
}
答案 27 :(得分:1)
好吧,在阅读了上述所有内容后,我觉得这些人已经过度复杂了将枚举数转换为字符串的问题。 我喜欢在枚举字段上使用属性的想法,但我认为属性主要用于元数据,但在您的情况下,我认为您需要的只是某种本地化。
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!
答案 28 :(得分:1)
基于MSDN:http://msdn.microsoft.com/en-us/library/cc138362.aspx
foreach (string str in Enum.GetNames(typeof(enumHeaderField)))
{
Debug.WriteLine(str);
}
str将是字段的名称
答案 29 :(得分:1)
对于较大的字符串枚举集,列出的示例可能会令人厌烦。如果需要状态代码列表或其他基于字符串的枚举列表,则使用属性系统很烦人,而带有自身实例的静态类则很烦人。对于我自己的解决方案,我使用T4模板来简化具有字符串支持的枚举的过程。结果类似于HttpMethod类的工作原理。
您可以像这样使用它:
string statusCode = ResponseStatusCode.SUCCESS; // Automatically converts to string when needed
ResponseStatusCode 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 values
bool 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();
}
}
}
答案 30 :(得分:0)
#1
'
some text 1
some text 2
some text 3
some text 4
some text 5
'
now doing thing A
#2
'
61
'
#3
'
some text 1
some text 2
some text 3
some text 4
some text 5
'
now doing thing B
#4
'
some text 1
some text 2
some text 3
some text 4
some text 5
'
输出为:
“表格”
“ WINDOWSAUTHENTICATION”
“ SINGLESIGNON”
答案 31 :(得分:0)
我和Harvey在一起,但不使用const。我可以混合和匹配string,int,等等。
public class xlsLayout
{
public int xlHeaderRow = 1;
public int xlFirstDataRow = 2;
public int xlSkipLinesBetweenFiles = 1; //so 0 would mean don't skip
public string xlFileColumn = "A";
public string xlFieldColumn = "B";
public string xlFreindlyNameColumn = "C";
public string xlHelpTextColumn = "D";
}
然后......
public partial class Form1 : Form
{
xlsLayout xlLayout = new xlsLayout();
xl.SetCell(xlLayout.xlFileColumn, xlLayout.xlHeaderRow, "File Name");
xl.SetCell(xlLayout.xlFieldColumn, xlLayout.xlHeaderRow, "Code field name");
xl.SetCell(xlLayout.xlFreindlyNameColumn, xlLayout.xlHeaderRow, "Freindly name");
xl.SetCell(xlLayout.xlHelpTextColumn, xlLayout.xlHeaderRow, "Inline Help Text");
}
答案 32 :(得分:0)
您可以声明枚举和字典,其中的键将是枚举的值。将来,您可以参考字典来获取值。因此,可以将参数作为枚举的类型传递给函数,但可以从字典中获取实际值:
using System;
using System.Collections.Generic;
namespace console_test
{
class Program
{
#region SaveFormat
internal enum SaveFormat
{
DOCX,
PDF
}
internal static Dictionary<SaveFormat,string> DictSaveFormat = new Dictionary<SaveFormat, string>
{
{ SaveFormat.DOCX,"This is value for DOCX enum item" },
{ SaveFormat.PDF,"This is value for PDF enum item" }
};
internal static void enum_value_test(SaveFormat save_format)
{
Console.WriteLine(DictSaveFormat[save_format]);
}
#endregion
internal static void Main(string[] args)
{
enum_value_test(SaveFormat.DOCX);//Output: This is value for DOCX enum item
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
答案 33 :(得分:0)
我很清楚这个问题已经得到解答,OP已经对接受的答案感到满意。但我发现大多数答案,包括接受的答案,都有点复杂。
我有一个项目给了我这样的情况,我能够以这种方式实现它。
首先,您必须考虑枚举名称的大小写:
public enum AuthenticationMethod
{
Forms = 1,
WindowsAuthentication = 2,
SingleSignOn = 3
}
然后,有这个扩展名:
using System.Text.RegularExpression;
public static class AnExtension
{
public static string Name(this Enum value)
{
string strVal = value.ToString();
try
{
return Regex.Replace(strVal, "([a-z])([A-Z])", "$1 $2");
}
catch
{
}
return strVal;
}
}
通过这个,您可以将每个枚举名称转换为其字符串表示形式,每个单词用空格分隔。例如:
AuthenticationMethod am = AuthenticationMethod.WindowsAuthentication;
MessageBox.Show(am.Name());
答案 34 :(得分:0)
我发现用于Enums国际化或从各个Resource文件获取Enums文本的方法是通过继承DescriptionAttribute类来创建属性类
public class EnumResourceAttribute : DescriptionAttribute
{
public Type ResourceType { get; private set; }
public string ResourceName { get; private set; }
public int SortOrder { get; private set; }
public EnumResourceAttribute(Type ResourceType,
string ResourceName,
int SortOrder)
{
this.ResourceType = ResourceType;
this.ResourceName = ResourceName;
this.SortOrder = SortOrder;
}
}
创建另一个静态类,它将为GetString和GetStrings提供扩展方法。
public static class EnumHelper
{
public static string GetString(this Enum value)
{
EnumResourceAttribute ea =
(EnumResourceAttribute)value.GetType().GetField(value.ToString())
.GetCustomAttributes(typeof(EnumResourceAttribute), false)
.FirstOrDefault();
if (ea != null)
{
PropertyInfo pi = ea.ResourceType
.GetProperty(CommonConstants.ResourceManager);
if (pi != null)
{
ResourceManager rm = (ResourceManager)pi
.GetValue(null, null);
return rm.GetString(ea.ResourceName);
}
}
return string.Empty;
}
public static IList GetStrings(this Type enumType)
{
List<string> stringList = new List<string>();
FieldInfo[] fiArray = enumType.GetFields();
foreach (FieldInfo fi in fiArray)
{
EnumResourceAttribute ea =
(EnumResourceAttribute)fi
.GetCustomAttributes(typeof(EnumResourceAttribute), false)
.FirstOrDefault();
if (ea != null)
{
PropertyInfo pi = ea.ResourceType
.GetProperty(CommonConstants.ResourceManager);
if (pi != null)
{
ResourceManager rm = (ResourceManager)pi
.GetValue(null, null);
stringList.Add(rm.GetString(ea.ResourceName));
}
}
}
return stringList.ToList();
}
}
关于你的Enum的元素你可以写:
public enum Priority
{
[EnumResourceAttribute(typeof(Resources.AdviceModule), Resources.ResourceNames.AdviceCreateAdviceExternaPriorityMemberHigh, 1)]
High,
[EnumResourceAttribute(typeof(Resources.AdviceModule), Resources.ResourceNames.AdviceCreateAdviceExternaPriorityMemberRoutine, 2)]
Routine
}
其中Resources.ResourceNames.AdviceCreateAdviceExternaPriorityMemberHigh&amp; Resources.ResourceNames.AdviceCreateAdviceExternaPriorityMemberRoutine是资源文件中的常量,或者您可以说其值可以在不同文化中使用的字符串。
如果要在MVC架构中实现Web应用程序,请创建属性
private IList result;
public IList Result
{
get
{
result = typeof(Priority).GetStrings();
return result;
}
}
在您的.cshtml文件中,您可以将枚举绑定到下拉列表,如:
@Html.DropDownListFor(model => Model.vwClinicalInfo.Priority, new SelectList(Model.Result))
由于 Ratnesh
答案 35 :(得分:0)
我的回答,处理@ user29964的答案(这是迄今为止最简单且最接近Enum的)是
public class StringValue : System.Attribute
{
private string _value;
public StringValue(string value)
{
_value = value;
}
public string Value
{
get { return _value; }
}
public static string GetStringValue(Enum Flagvalue)
{
Type type = Flagvalue.GetType();
string[] flags = Flagvalue.ToString().Split(',').Select(x => x.Trim()).ToArray();
List<string> values = new List<string>();
for (int i = 0; i < flags.Length; i++)
{
FieldInfo fi = type.GetField(flags[i].ToString());
StringValue[] attrs =
fi.GetCustomAttributes(typeof(StringValue),
false) as StringValue[];
if (attrs.Length > 0)
{
values.Add(attrs[0].Value);
}
}
return String.Join(",", values);
}
使用
[Flags]
public enum CompeteMetric
{
/// <summary>
/// u
/// </summary>
[StringValue("u")]//Json mapping
Basic_UniqueVisitors = 1 //Basic
,
/// <summary>
/// vi
/// </summary>
[StringValue("vi")]//json mapping
Basic_Visits = 2// Basic
,
/// <summary>
/// rank
/// </summary>
[StringValue("rank")]//json mapping
Basic_Rank = 4//Basic
}
实施例
CompeteMetric metrics = CompeteMetric.Basic_Visits | CompeteMetric.Basic_Rank;
string strmetrics = StringValue.GetStringValue(metrics);
这将返回 “vi中,等级”
答案 36 :(得分:0)
使用对象Enum.Parse(System.Type enumType,string value,bool ignoreCase); 从http://blogs.msdn.com/b/tims/archive/2004/04/02/106310.aspx获取