我刚刚看到使用 if(!(a == b))
而不是 C# 中更常见的 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# 编译器需要了解的事情。
关于c# - !(a == b) 和 a != b 有区别吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56136103/