When are two enums equal in C#?

前端 未结 7 1797
栀梦
栀梦 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:19

    I refer you to the C# Language Specification v3.0, from which this quote has been extracted from the Enum section on page 29:

    "Each enum type has a corresponding integral type called the underlying type of the enum type. An enum type that does not explicitly declare an underlying type has an underlying type of int. An enum type’s storage format and range of possible values are determined by its underlying type. The set of values that an enum type can take on is not limited by its enum members. In particular, any value of the underlying type of an enum can be cast to the enum type and is a distinct valid value of that enum type."

    The .AreEqual method is really testing equivalence while the second tests identity. So, simply cast each one to its underlying type (in this case, int) and then do the comparison.

    public enum enumA { one, two }
    public enum enumB { one, two }
    [Test]
    public void PreTest()
    {
            Assert.AreEqual((int)enumA.one,(int)enumB.one);
            Assert.AreSame(enumA.one, enumB.one);
    }
    

提交回复
热议问题