How to get right result of ToString() method in enum with two equal items

后端 未结 4 1749
礼貌的吻别
礼貌的吻别 2021-01-26 00:38

I have enum

[Flags]
public enum MyEnum
{
   Item1 = 32768,
   Item2 = 65536,
   Item3 = 524288,
   Item4 = Item3
}

Results of ToString() operat

4条回答
  •  旧巷少年郎
    2021-01-26 01:02

    Firstly, I don't understand why you need two items with the same value. However, if you need the same enum values but want the different names later, perhaps try using the DescriptionAttribute in System.ComponentModel?

    [Flags]
    public enum MyEnum
    {
       [DescriptionAttribute("Item1")]Item1 = 32768,
       [DescriptionAttribute("Item2")]Item2 = 65536,
       [DescriptionAttribute("Item3")]Item3 = 524288,
       [DescriptionAttribute("Item4")]Item4 = Item3
    }
    

    Then you could this method to get the description value back:

    public string ValueOf(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();
        }
    }
    

    I've not actually tried this out, so the MSDN quote @MarcinJuraszek posted might still apply here.

    Source: http://blog.waynehartman.com/articles/84.aspx

提交回复
热议问题