Can you have multiple enum values for the same integer? [duplicate]

走远了吗. 提交于 2019-12-28 06:37:24

问题


In .NET can you have multiple enum values for the same integer?

eg.

public enum PersonGender
    {
        Unknown = 0,
        Male = 1,
        Female = 2,
        Intersex = 3,
        Indeterminate = 3,
        NonStated = 9,
        InadequatelyDescribed = 9
    }

回答1:


In C#, this is allowed, as per the C# Language Specication, version 4.

Section 1.10 Enums doesn't mention the possibility but later on in section 14 Enums, we see (in 14.3):


Multiple enum members may share the same associated value. The example

enum Color {
   Red,
   Green,
   Blue,
   Max = Blue
}

shows an enum in which two enum members - Blue and Max - have the same associated value.




回答2:


That works fine. There is absolutely nothing wrong with the code you posted. It compiles just fine and works in code, with the caveat that

PersonGender.NonStated == PersonGender.InadequatelyDescribed



回答3:


I found this StackOverflow post related to this question. I think there is a very sensible discussion of how this works. Non-unique enum values

Now, I might also add that it is my opinion this would be an ambiguous (and therefore improper) use of an enum. It's important to write code that makes sense to someone else reading it, and in this case, I would be put off by this enum.




回答4:


I would suggest that an enum would not be a right thing to use in your context instead you can use create a class and methods which can resolve your purpose. Something like this in your class:-

class A
{

    static readonly ABCD= new Dictionary<int,string>
        {
            { 1, "X" },
            { 2, "X" },
            { 3, "Y" }
            { 4, "Y" }
        }
}


来源:https://stackoverflow.com/questions/15458101/can-you-have-multiple-enum-values-for-the-same-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!