首页 > 解决方案 > !(a == b) 和 a != b 之间有区别吗

问题描述

我刚刚看到了使用的代码,而不是C#if(!(a == b))中更常见的代码。if(a != b)我想知道C#中两者之间是否有区别?

标签: 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# 编译器需要知道的事情。


推荐阅读