📜  C# 枚举键值 - C# 代码示例

📅  最后修改于: 2022-03-11 14:48:45.641000             🧑  作者: Mango

代码示例1
public enum infringementCategory
{ 
    [Description("INF0001")]
    Infringement,
    [Description("INF0002")]
    OFN
}

public static class EnumExtension
{
    /// 
    /// Gets the string of an DescriptionAttribute of an Enum.
    /// 
    /// The Enum value for which the description is needed.
    /// If a DescriptionAttribute is set it return the content of it.
    /// Otherwise just the raw name as string.
    public static string Description(this Enum value)
    {
        if (value == null)
        {
            throw new ArgumentNullException("value");
        }

        string description = value.ToString();
        FieldInfo fieldInfo = value.GetType().GetField(description);
        DescriptionAttribute[] attributes =
           (DescriptionAttribute[])
         fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attributes != null && attributes.Length > 0)
        {
            description = attributes[0].Description;
        }

        return description;
    }

    /// 
    /// Creates an List with all keys and values of a given Enum class
    /// 
    /// Must be derived from class Enum!
    /// A list of KeyValuePair with all available
    /// names and values of the given Enum.
    public static IList> ToList() where T : struct
    {
        var type = typeof(T);

        if (!type.IsEnum)
        {
            throw new ArgumentException("T must be an enum");
        }

        return (IList>)
                Enum.GetValues(type)
                    .OfType()
                    .Select(e => new KeyValuePair(e, e.Description()))
                    .ToArray();
    }

    public static T GetValueFromDescription(string description) where T : struct
    {
        var type = typeof(T);

        if(!type.IsEnum)
        {
            throw new ArgumentException("T must be an enum");
        }

        foreach(var field in type.GetFields())
        {
            var attribute = Attribute.GetCustomAttribute(field,
                typeof(DescriptionAttribute)) as DescriptionAttribute;

            if(attribute != null)
            {
                if(attribute.Description == description)
                {
                    return (T)field.GetValue(null);
                }
            }
            else
            {
                if(field.Name == description)
                {
                    return (T)field.GetValue(null);
                }
            }
        }

        throw new ArgumentOutOfRangeException("description");
        // or return default(T);
    }
}