我有以下列举:

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

然而问题是,当我请求AuthenticationMethod时,我需要“FORMS”这个词。表单而不是id

对于这个问题,我找到了以下解决方案(链接):

首先,我需要创建一个自定义属性“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);

好的,现在所有这些工作就像一个魅力,但我发现它有很多工作。我想知道有没有更好的解决办法。

我还尝试了一些字典和静态属性,但这也不是更好。


当前回答

当我遇到这样的问题时,我首先会试图找到以下几个问题的答案:

枚举值的名称是否足够友好,或者我需要提供更友好的名称? 我需要往返吗?也就是说,我是否需要将文本值解析为枚举值? 这是我需要为我的项目中的许多枚举做的事情,还是只有一个? 我将在什么样的UI元素中呈现这些信息-特别是,我将绑定到UI,还是使用属性表? 这需要本地化吗?

最简单的方法是使用Enum。GetValue(并使用枚举. parse支持往返)。正如Steve Mitcham所建议的那样,构建一个TypeConverter来支持UI绑定通常也是值得的。(在使用属性表时,没有必要构建TypeConverter,这是属性表的优点之一。尽管天晓得他们也有自己的问题。)

一般来说,如果上述问题的答案表明这是行不通的,我的下一步是创建和填充一个静态Dictionary<MyEnum,字符串>,或者可能是一个Dictionary<Type, Dictionary<int,字符串>>。我倾向于跳过中间的用属性装饰代码的步骤,因为接下来通常需要在部署后更改友好值(通常,但不总是,因为本地化)。

其他回答

我同意基斯的意见,但我还不能投票。

我使用一个静态方法和swith语句来返回我想要的结果。在数据库中,我存储tinyint和我的代码只使用实际的enum,所以字符串是为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;
     }
}

然而,根据某些说法,这可能会导致维护的噩梦和一些代码异味。我试着留意那些很长很多的枚举,或者那些经常变化的枚举。除此之外,这对我来说是一个很好的解决方案。

用. net 4.0及以上版本解决这个问题非常简单。不需要其他代码。

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

获取字符串about只需使用:

MyStatus.Active.ToString("f");

or

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

取值为Active或Archived。

当调用Enum时,查看不同的字符串格式(上面的“f”)。ToString参见此枚举格式字符串页面

如果你想一下我们要解决的问题,它根本不是我们需要的枚举。我们需要一个对象,它允许一定数量的值相互关联;换句话说,定义一个类。

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

看看它:

它有一个私有构造函数,因此只有类本身可以定义允许的值。 它是一个密封类,因此不能通过继承修改值。 它是类型安全的,允许您的方法只需要该类型。 访问这些值不会对反射性能造成影响。 最后,可以修改它以将两个以上的字段关联在一起,例如Name、Description和numeric Value。

我很清楚这个问题已经被回答了,而且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());

我的变体

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)。