枚举拳击和平等
为什么这个返回 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;
}
而这个返回 True?
public static bool IsOneOf(Enum self, params Enum[] values)
{
foreach (var value in values)
if (self.Equals(value))
return true;
return false;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Enum 不实现 == 相等运算符,但它会重写 Equals 方法。
由于它没有实现 ==,系统会执行引用相等性检查。 请注意,System.Enum 是一个类而不是一个结构。 因此,诸如 Directions.Left 之类的值会被装箱。 在这种特殊情况下,装箱的对象最终成为单独的对象,因此它们无法通过引用相等性测试。
编译器理解具体 Enum 类型(例如 Directions)的 ==,但编译器不会针对 System.Enum 类型进行这种特殊处理。
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.
正如 JB 所说,拳击。 看到这一点。
您可以通过从 Enum 更改为 Directions: true 返回来
As JB says, boxing. You can see this by changing from Enum to Directions:
true is returned.