解析字符串以匹配枚举值

时间:2012-03-07 08:49:26

标签: c# enums

如果我有一个char的枚举

public enum Action
{
    None,
    Address = 'A',
    Amendment = 'C',
    Normal = 'N'
}

解析单个字符串以匹配相应的枚举字符的最佳方法是什么,如果未找到则匹配None。 TryParse匹配Name而不是值。

例如,如果我的字符串是“C”,我想获得Action.Amendement

提前致谢

5 个答案:

答案 0 :(得分:5)

char c = 'C'; // existent value
var action = Enum.GetValues(typeof(Action)).Cast<Action>().FirstOrDefault(a => (char)a == c);
// action = Action.Amendment

char c = 'X'; // non existent value
var action = Enum.GetValues(typeof(Action)).Cast<Action>().FirstOrDefault(a => (char)a == c);
// action = Action.None

答案 1 :(得分:4)

投下它:

Action f = (Action)'C';

如果你有一个字符串并且是肯定的,那么你至少可以做一个字符:

Action f = (Action)"C"[0];

答案 2 :(得分:3)

我个人将它们保留为整数,并使用DescriptionAttributes和实用程序类来获取该类型的描述属性。然后你可以使用的不仅仅是一个角色来展示你想要的东西。

这方面的一个例子是;

    /// <summary>
    /// Returns the string value defined by the description attribute of the given enum.
    /// If no description attribute is available, then it returns the string representation of the enum.
    /// </summary>
    /// <param name="value">Enum to use</param>
    /// <returns>String representation of enum using Description attribute where possible</returns>
    public static string StringValueOf(Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());
        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (attributes.Length > 0)
        {
            return attributes[0].Description;
        }
        else
        {
            return value.ToString();
        }
    }

你的枚举被定义为类似的东西;

public enum Action
{
    None,
    [DescriptionAttribute("A")]
    Address,
    [DescriptionAttribute("C")]
    Amendment,
    [DescriptionAttribute("N")]
    Normal
}

答案 3 :(得分:0)

枚举是幕后的数字类型。你可以尝试一类公共字符串:

public class Action()
{
    public const string A = "Address";
    public const string C = "Amendment";
}

如果你想以2种方式做,那么你可能想要使用双向字典集。

答案 4 :(得分:0)

基于@Mose先生,我想提供2美分的代码。它包含相同的方法,但也包含反向方法。因此,在序列化反序列化的情况下,可以将其组合。

在您的代码中包含一个EnumExtensions类:

using System.ComponentModel;
using System.Linq;
using System.Reflection;

public static class EnumExtensions
{
    /// <summary>
    /// Converts the bare enum value to a string using the <see cref="DescriptionAttribute"/>
    /// that was appplied to it.
    /// </summary>
    /// <typeparam name="TEn"></typeparam>
    /// <param name="enumValue"></param>
    /// <returns></returns>
    public static string ToDescription<TEn>(this TEn enumValue) where TEn : struct
    {
        FieldInfo fi = enumValue.GetType().GetField(enumValue.ToString());

        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

        return attributes.Length > 0 ? attributes[0].Description : enumValue.ToString();
    }

    /// <summary>
    /// Does the reverse lookup. If there is an enum member with the string <paramref name="enumString"/>
    /// as <see cref="DescriptionAttribute"/> it will be returned, otherwise the fallback value in
    /// <paramref name="fallback"/> will be returned.
    /// </summary>
    /// <typeparam name="TEn">Type of the enum in question.</typeparam>
    /// <param name="enumString">String serialization of Description annotated enum.</param>
    /// <param name="fallback">Default value to return.</param>
    /// <returns>Either the found value or the fallback.</returns>
    public static TEn FromDescription<TEn>(this string enumString, TEn fallback = default(TEn)) where TEn : struct
    {
        if (enumString != null)
        {
            FieldInfo[] fieldInfo = typeof(TEn).GetFields();

            foreach (var fi in fieldInfo)
            {
                DescriptionAttribute[] attributes =
                    (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attributes.Any(att => att.Description == enumString))
                {
                    object rawConstantValue = fi.GetRawConstantValue();
                    return (TEn)rawConstantValue;
                }
            }
        }

        return fallback;
    }
}

并向Enums提供DescriptionAttribute,如前所述:

public enum ComparisonOperators
{
    [Description("=")]
    Equal,

    [Description("<>")]
    Unequal,

    [Description("<")]
    LessThan,

    [Description("<=")]
    LessThanOrEqual,

    [Description(">")]
    GreaterThan,

    [Description(">=")]
    GreaterThanOrEqual
}

像这样使用它:

string v = "<>";
ComparisonOperators x = v.FromDescription(ComparisonOperators.Equal);
string w = x.ToDescription();
Debug.Assert(v==w);  //ok