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

后端 未结 4 1737
礼貌的吻别
礼貌的吻别 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 00:40

    No, you can't.

    If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of an enumeration member's name based on its underlying value, your code should not make any assumptions about which name the method will return.

    Enum.ToString() Method

    0 讨论(0)
  • 2021-01-26 00:46

    No, because you set Item4 to be equal to Item3, and as they're just typesafe ints (enums are), the CLR can't tell the difference.

    Try setting Item4 to a different value to get the expected result.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-26 01:06

    No, because enum aren't collections of strings. They are value types that can contain an integral of a certain type (normally an int), where some of these integrals are connected to a "name" (your Item4)

    0 讨论(0)
提交回复
热议问题