C#中的两个枚举是什么时候相等? [英] When are two enums equal in C#?

查看:555
本文介绍了C#中的两个枚举是什么时候相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了两个枚举,我知道他们不是相同的,但是我认为这是有意义的,因为他们的字符串表示以及它们的数字是相等的表示是相等的(甚至相同的...)。

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 representation as well as their numeral representation are equal (and even the same...).

换句话说:我想要第一个测试通过,第二个测试失败。然而,在现实中,他们都失败了。那么C#中的两个枚举是什么时候呢?还是在C#中定义equals运算符?

In other words : I would like the first test to pass and the second one to fail. In reality however, they both fail. So : when are two enums in C# equal? Or is there anyway to define the equals operator in C#?

谢谢!

    public enum enumA {one, two}

    public enum enumB {one, two}

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

更新:1)所以答案到目前为止都比较表示,无论是int或字符串。枚举本身永远是不平等的我收集?没有办法为它定义平等?

UPDATE : 1) So the answers so far all compare representations, be it ints or strings. The enum itself is always unequal I gather? No means to define equality for it?

推荐答案

枚举是强类型的C#,因此 enumA.one != enumB.one 。现在,如果您将每个枚举转换为整数值,它们将相等。

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);

此外,我想挑战该语句,因为它们具有相同的整数或字符串表示形式它们应该是相同或相等的。给定两个枚举 NetworkInterface VehicleType ,C#或.Net框架允许 NetworkInterface.None 等于 VehicleType.None 当与枚举进行比较时,通过任一值或字符串。但是,如果开发人员将强类型枚举转换为整数或字符串,则语言或框架无法阻止两者相等。

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.

为了进一步澄清,为了提供不同的相等方法,您不能覆盖 MyEnum.Equals 。 .Net枚举不是Java以后的第一类公民,我希望C#允许与Enums进行更丰富的交互。

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.

这篇关于C#中的两个枚举是什么时候相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆