当两个枚举等于在C#中? [英] When are two enums equal in C#?

查看:194
本文介绍了当两个枚举等于在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#中的相等操作符?

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)所以答案为止所有的比较表示,无论是整型或字符串。枚举的本身的始终是不平等的我收集?没有办法为他定义平等?

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 Framework允许 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#允许使用枚举更丰富的互动。

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天全站免登陆