c# - !(a == b) 和 a != b 之间有区别吗
问题描述
我刚刚看到了使用的代码,而不是C#if(!(a == b))
中更常见的代码。if(a != b)
我想知道C#中两者之间是否有区别?
解决方案
在大多数情况下,它们是相同的——但它们不必相同。!=
并且==
可以单独重载,具有不同的逻辑。这是一个例子:
using System;
class Test
{
// All this code is awful. PURELY FOR DEMONSTRATION PURPOSES.
public static bool operator==(Test lhs, Test rhs) => true;
public static bool operator!=(Test lhs, Test rhs) => true;
public override bool Equals(object other) => true;
public override int GetHashCode() => 0;
static void Main()
{
Test a = null;
Test b = null;
Console.WriteLine(a != b); // True
Console.WriteLine(!(a == b)); // False
}
}
在绝大多数情况下,a != b
都会!(a == b)
有完全相同的行为,而且a != b
几乎总是更清晰。但值得注意的是,它们可能有所不同。
它会变得更加病态——a != b
甚至!(a == b)
可能有不同的类型。例如:
using System;
class Test
{
// All this code is awful. PURELY FOR DEMONSTRATION PURPOSES.
public static Test operator==(Test lhs, Test rhs) => new Test();
public static Test operator!=(Test lhs, Test rhs) => new Test();
public static string operator!(Test lhs) => "Negated";
public override string ToString() => "Not negated";
public override bool Equals(object other) => true;
public override int GetHashCode() => 0;
static void Main()
{
Test a = null;
Test b = null;
Console.WriteLine(a != b); // "Not negated"
Console.WriteLine(!(a == b)); // "Negated"
}
}
这里a != b
是类型Test
,但是!(a == b)
是类型string
。是的,这太可怕了,你不太可能在现实生活中遇到它——但这是 C# 编译器需要知道的事情。
推荐阅读
- php - 检查多维数组的所有值是否为空
- amazon-web-services - 默认响应标头:带代理集成的 AWS API Gateway
- django - 与服务人员反应生产错误:无效的 MIME 类型
- node.js - 节点 js - 错误 [ERR_IPC_CHANNEL_CLOSED]:通道关闭
- windows - 已安装具有给定服务名称的 tomcat 服务
- c++ - 最大回文数(如果从左到右或从右到左阅读,它是相同的数字)
- javascript - 将本地组件文件导入我的 LoginForm 组件时出错
- ckan - 从 JavaScript 验证/登录到 CKAN
- json - 如何在 Elm 中操作 Json.Encode.Value?
- java - 使用 Chronicle Map 作为微服务之间的数据共享手段