gpt4 book ai didi

c# - !(a == b) 和 a != b 有区别吗

转载 作者:IT王子 更新时间:2023-10-29 04:18:04 26 4
gpt4 key购买 nike

我刚刚看到使用 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 != bTest 类型,但是 !(a == b)string。是的,这太可怕了,您在现实生活中不太可能遇到它 - 但这是 C# 编译器需要了解的事情。

关于c# - !(a == b) 和 a != b 有区别吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56136103/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com