When are two enums equal in C#?

前端 未结 7 1739
栀梦
栀梦 2020-12-31 22:39

I have created two enums and I know they are not the same but still I think it makes sense they would be equal since their string represent

相关标签:
7条回答
  • 2020-12-31 23:32

    Enums are strongly typed in C#, hence enumA.one != enumB.one. Now, if you were convert each enum to their integer value, they would be equal.

    Assert.AreEqual((int)enumA.one, (int)enumB.one);
    

    Also, I'd like to challenge the statement that because they have the same integer or string representation that they should be the same or equals. Given two enumerations NetworkInterface and VehicleType, it would not be logical for C# or the .Net Framework to allow NetworkInterface.None to equal VehicleType.None when compared as enumeration, by either value or string. However, if the developer cast the strongly typed enumeration to an integer or string, there is nothing the language or framework can do to stop the two from being equals.

    To further clarify, you cannot override MyEnum.Equals in order to provide a different equality method. .Net enums are not quite the first class citizens they are in later versions of Java, and I wish that C# allowed for richer interactions with Enums.

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