枚举拳击与平等 [英] Enum Boxing and Equality
问题描述
为什么这返回false
公共枚举路线{上,下,左,右}
静态无效的主要(字串[] args)
{
布尔匹配= IsOneOf(Directions.Right,Directions.Left,Directions.Right);
Console.WriteLine(匹配);
Console.Read();
}
公共静态布尔IsOneOf(枚举自我,PARAMS枚举[]值)
{
的foreach(中值VAR值)
如果(自==值)
返回true;
返回FALSE;
}
而返回true?
公共静态布尔IsOneOf(枚举自我,PARAMS枚举[]值)
{
的foreach(中值VAR值)
如果(自.Equals(值))
返回真;
返回FALSE;
}
枚举没有实现= =等于运算符,但它确实重写Equals方法。
由于没有实现==,系统将执行一个参考平等检查。注意,System.Enum是一个类不是一个结构。因此,如Directions.Left值装箱。在这种特殊情况下,盒装对象最终被单独的对象,因此,他们没有一个参考平等的考验。
,编译器理解==混凝土枚举类型(如路线),但是编译器不会做对System.Enum类型此特殊处理。
Why does this return False
public enum Directions { Up, Down, Left, Right }
static void Main(string[] args)
{
bool matches = IsOneOf(Directions.Right, Directions.Left, Directions.Right);
Console.WriteLine(matches);
Console.Read();
}
public static bool IsOneOf(Enum self, params Enum[] values)
{
foreach (var value in values)
if (self == value)
return true;
return false;
}
while this returns True?
public static bool IsOneOf(Enum self, params Enum[] values)
{
foreach (var value in values)
if (self.Equals(value))
return true;
return false;
}
Enum does not implement a == equality operator but it does override the Equals method.
Since it does not implement ==, the system performs a reference equality check. Note that System.Enum is a class not a structure. Hence, values such as Directions.Left are boxed. In this particular case, the boxed objects end up being separate objects, hence they fail a reference equality test.
The compiler understands == for concrete Enum types (such as Directions), but the compiler does not do this special processing against the System.Enum type.
这篇关于枚举拳击与平等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!