作为枚举的键值对

发布于 2024-10-16 06:42:58 字数 218 浏览 1 评论 0原文

我可以有一个充当键值对的枚举吗?

public enum infringementCategory
{ 
    Infringement,
    OFN
}

如果我选择Infringement,我应该得到“INF0001”,如果我选择OFN,我应该得到“INF0002”

这可能吗?

Can I have an enum which acts as a key value pair.

public enum infringementCategory
{ 
    Infringement,
    OFN
}

If I select Infringement I should get "INF0001" and if I select OFN I should get "INF0002"

Is it possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

千仐 2024-10-23 06:42:58

您可以使用装饰器将字符串表示形式与枚举值关联起来。检查这个问题:带有用户友好字符串的Enum ToString

它看起来像:

public enum infringementCategory
{ 
    [Description("INF0001")]
    Infringement,
    [Description("INF0002")]
    OFN
}

看起来比使用字典更整洁,并且需要更少维持。

You can use decorators in order to associate string representation with your enum values. Check this question: Enum ToString with user friendly strings

It will look like:

public enum infringementCategory
{ 
    [Description("INF0001")]
    Infringement,
    [Description("INF0002")]
    OFN
}

Looks more neat than using Dictionary and needs less maintain.

知足的幸福 2024-10-23 06:42:58

这些扩展怎么样:

public static class EnumExtension
{
    /// <summary>
    /// Gets the string of an DescriptionAttribute of an Enum.
    /// </summary>
    /// <param name="value">The Enum value for which the description is needed.</param>
    /// <returns>If a DescriptionAttribute is set it return the content of it.
    /// Otherwise just the raw name as string.</returns>
    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;
    }

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

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

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

    public static T GetValueFromDescription<T>(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);
    }
}

有了这个,你可以像这样构建你的枚举:

public enum Foo
{
    [Description("Foo - Something")]
    Something,
    [Description("Foo - Anything")]
    Anything,
}

并像这样获取你的列表:

var list = EnumExtension.ToList<Foo>();

How about these extensions:

public static class EnumExtension
{
    /// <summary>
    /// Gets the string of an DescriptionAttribute of an Enum.
    /// </summary>
    /// <param name="value">The Enum value for which the description is needed.</param>
    /// <returns>If a DescriptionAttribute is set it return the content of it.
    /// Otherwise just the raw name as string.</returns>
    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;
    }

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

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

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

    public static T GetValueFromDescription<T>(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);
    }
}

With this in place you can built up your enum like this:

public enum Foo
{
    [Description("Foo - Something")]
    Something,
    [Description("Foo - Anything")]
    Anything,
}

And get your list like this:

var list = EnumExtension.ToList<Foo>();
西瑶 2024-10-23 06:42:58

您可以将标题 (INF0001)...存储在 Dictionary

You could store the titles (INF0001)... in a Dictionary<infringementCategory, string>

┼── 2024-10-23 06:42:58

请参阅:

public enum InfringementCategory
{
    [EnumNamedConstant(Description = "INF0001")]
    Infringement,

    [EnumNamedConstant(Description = "INF0002")]
    OFN
}

public class Test{
    public void Test()
    {
        String result = InfringementCategory.Infringement.GetDescription();
    }
}

这里是扩展方法......

#region [ EnumNamedConstantAttribute ]
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class EnumNamedConstantAttribute : Attribute
{
    public string Description { get; set; }
    public string Value { get; set; }
}
#endregion


#region EnumUtilities
public static class EnumUtilities
{
    #region [ + Extension Methods ]

    #region [ GetDescription ]

    public static string GetDescription(this Enum constant)
    {
        return EnumUtilities.GetEnumNamedConstantAttribute(constant).Description;
    }
    #endregion

    #region [ GetStringValue ]

    public static string GetStringValue(this Enum constant)
    {
        return GetEnumNamedConstantValue(constant);
    }
    #endregion

    #endregion

    #region [ + Static Methods ]

    #region [ GetEnumerable ]

    public static IEnumerable<EnumNamedConstantAttribute> GetEnumerable<T>()
    {
        T instancia = Activator.CreateInstance<T>();

        FieldInfo[] objInfos = instancia.GetType().GetFields(BindingFlags.Public | BindingFlags.Static);
        foreach (FieldInfo objFileInfo in objInfos)
        {
            Enum constant = (Enum)objFileInfo.GetValue(objFileInfo);
            if (objFileInfo.GetCustomAttributes(typeof(EnumNamedConstantAttribute), false).Length != 0)
            {
                yield return new EnumNamedConstantAttribute()
                {
                    Description = EnumUtilities.GetEnumNamedConstantAttribute(constant).Description,
                    Value = GetEnumNamedConstantValue(constant)
                };
            }
        }
    }
    #endregion

    #endregion

    #region [ + Privates ]

    #region [ GetEnumNamedConstantAttribute ]
    private static EnumNamedConstantAttribute GetEnumNamedConstantAttribute(Enum constant)
    {
        FieldInfo[] objInfos = constant.GetType().GetFields(BindingFlags.Public | BindingFlags.Static);
        foreach (FieldInfo objFileInfo in objInfos)
        {
            Enum constantItem = (Enum)objFileInfo.GetValue(objFileInfo);
            if (constantItem.GetHashCode().Equals(constant.GetHashCode()))
            {
                object[] attributes = objFileInfo.GetCustomAttributes(typeof(EnumNamedConstantAttribute), false);

                if (attributes.Length > 0)
                    return (EnumNamedConstantAttribute)attributes[0];
            }
        }
        return null;
    }
    #endregion

    #region [ GetEnumNamedConstantValue ]
    private static string GetEnumNamedConstantValue(Enum constant)
    {
        string sValue = (constant.GetHashCode()).ToString();
        EnumNamedConstantAttribute objRet = EnumUtilities.GetEnumNamedConstantAttribute(constant);
        if (objRet != null)
        {
            String sAux = objRet.Value;
            if (!String.IsNullOrEmpty(sAux))
                sValue = objRet.Value;
        }
        return sValue;
    }
    #endregion

    #endregion
}
#endregion

See:

public enum InfringementCategory
{
    [EnumNamedConstant(Description = "INF0001")]
    Infringement,

    [EnumNamedConstant(Description = "INF0002")]
    OFN
}

public class Test{
    public void Test()
    {
        String result = InfringementCategory.Infringement.GetDescription();
    }
}

And here the extension methods...

#region [ EnumNamedConstantAttribute ]
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class EnumNamedConstantAttribute : Attribute
{
    public string Description { get; set; }
    public string Value { get; set; }
}
#endregion


#region EnumUtilities
public static class EnumUtilities
{
    #region [ + Extension Methods ]

    #region [ GetDescription ]

    public static string GetDescription(this Enum constant)
    {
        return EnumUtilities.GetEnumNamedConstantAttribute(constant).Description;
    }
    #endregion

    #region [ GetStringValue ]

    public static string GetStringValue(this Enum constant)
    {
        return GetEnumNamedConstantValue(constant);
    }
    #endregion

    #endregion

    #region [ + Static Methods ]

    #region [ GetEnumerable ]

    public static IEnumerable<EnumNamedConstantAttribute> GetEnumerable<T>()
    {
        T instancia = Activator.CreateInstance<T>();

        FieldInfo[] objInfos = instancia.GetType().GetFields(BindingFlags.Public | BindingFlags.Static);
        foreach (FieldInfo objFileInfo in objInfos)
        {
            Enum constant = (Enum)objFileInfo.GetValue(objFileInfo);
            if (objFileInfo.GetCustomAttributes(typeof(EnumNamedConstantAttribute), false).Length != 0)
            {
                yield return new EnumNamedConstantAttribute()
                {
                    Description = EnumUtilities.GetEnumNamedConstantAttribute(constant).Description,
                    Value = GetEnumNamedConstantValue(constant)
                };
            }
        }
    }
    #endregion

    #endregion

    #region [ + Privates ]

    #region [ GetEnumNamedConstantAttribute ]
    private static EnumNamedConstantAttribute GetEnumNamedConstantAttribute(Enum constant)
    {
        FieldInfo[] objInfos = constant.GetType().GetFields(BindingFlags.Public | BindingFlags.Static);
        foreach (FieldInfo objFileInfo in objInfos)
        {
            Enum constantItem = (Enum)objFileInfo.GetValue(objFileInfo);
            if (constantItem.GetHashCode().Equals(constant.GetHashCode()))
            {
                object[] attributes = objFileInfo.GetCustomAttributes(typeof(EnumNamedConstantAttribute), false);

                if (attributes.Length > 0)
                    return (EnumNamedConstantAttribute)attributes[0];
            }
        }
        return null;
    }
    #endregion

    #region [ GetEnumNamedConstantValue ]
    private static string GetEnumNamedConstantValue(Enum constant)
    {
        string sValue = (constant.GetHashCode()).ToString();
        EnumNamedConstantAttribute objRet = EnumUtilities.GetEnumNamedConstantAttribute(constant);
        if (objRet != null)
        {
            String sAux = objRet.Value;
            if (!String.IsNullOrEmpty(sAux))
                sValue = objRet.Value;
        }
        return sValue;
    }
    #endregion

    #endregion
}
#endregion
断桥再见 2024-10-23 06:42:58

更新:
感谢 Oliver 指出 System.Component.DescriptionAttribute 。操作方法如下:

public enum infringementCategory
{
    [Description("INF0001")]
    Infringement,
    [Description("INF0002")]
    OFN
}

public static class DescriptionExtensions
{
    public static string GetDescriptionValue(this Enum value)
    {
        // Get the type
        Type type = value.GetType();

        // Get fieldinfo for this type
        FieldInfo fieldInfo = type.GetField(value.ToString());

        // Get the stringvalue attributes
        DescriptionAttribute[] attribs = fieldInfo.GetCustomAttributes(
            typeof(DescriptionAttribute), false) as DescriptionAttribute[];

        // Return the first if there was a match.
        return attribs.Length > 0 ? attribs[0].Description : null;
    }
}

public class Program
{
    static void Main(string[] args)
    {
        infringementCategory category = infringementCategory.OFN;
        string description = category.GetDescriptionValue();
    }
}

Update:
Thanks to Oliver for pointing out System.Component.DescriptionAttribute. Here's how to do it:

public enum infringementCategory
{
    [Description("INF0001")]
    Infringement,
    [Description("INF0002")]
    OFN
}

public static class DescriptionExtensions
{
    public static string GetDescriptionValue(this Enum value)
    {
        // Get the type
        Type type = value.GetType();

        // Get fieldinfo for this type
        FieldInfo fieldInfo = type.GetField(value.ToString());

        // Get the stringvalue attributes
        DescriptionAttribute[] attribs = fieldInfo.GetCustomAttributes(
            typeof(DescriptionAttribute), false) as DescriptionAttribute[];

        // Return the first if there was a match.
        return attribs.Length > 0 ? attribs[0].Description : null;
    }
}

public class Program
{
    static void Main(string[] args)
    {
        infringementCategory category = infringementCategory.OFN;
        string description = category.GetDescriptionValue();
    }
}
梦行七里 2024-10-23 06:42:58

您有多种选择:

  1. vc74 建议的字典。这是高效的,并且可以将枚举与属性解耦。

  2. switch 语句

  3. 如果您只想与每个语句关联一个整数,则可以使用:

     公共枚举 InfringementCategory
     { 
         侵权=1,
         OFN = 2
     }
    

    然后将(int)myEnum放入String.Format中,将其转换为您想要的形式的字符串。

  4. 属性

    公共枚举 InfringementCategory
    { 
        [InfID("INF0001")]侵权,
        [InfID("INF0002")]OFN
    }
    

    为了提高性能,您可以使用一次反射来填充字典。

You have a number of choices:

  1. A Dictionary as vc74 suggested. This is efficient and decouples your enum from the property.

  2. A switch statement

  3. If the only thing you want to associate with each is an integer you can use:

     public enum InfringementCategory
     { 
         Infringement = 1,
         OFN = 2
     }
    

    and then put (int)myEnum into String.Format to turn it into a string of the form you want.

  4. An Attribute

    public enum InfringementCategory
    { 
        [InfID("INF0001")]Infringement,
        [InfID("INF0002")]OFN
    }
    

    For improved performance you can use reflection once to populate dictionary.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文