【问题标题】:What is the difference between "is not null" and "!= null"?“不为空”和“!=空”有什么区别?
【发布时间】:2021-11-14 21:57:01
【问题描述】:

随着 C# 9.0 的发布,引入了 negated null constant 模式。

文档说明:

从 C# 9.0 开始,您可以使用取反的 null 常量模式来检查非 null,如以下示例所示:

if (e is not null)
{
    // ...
}

e is not nulle != null除了语法有区别吗?

【问题讨论】:

  • Constant pattern: "编译器保证不会调用用户重载的相等运算符 == ..."
  • 有趣的是,您为问题复制的文本是您正在寻找的答案下方的一行
  • 哈!!然后得到了答案:) 谢谢,我没有发现。
  • 基本上编译器会将其转换为(object)e!= null,从而确保不涉及讨厌的重载相等运算符
  • “讨厌的重载相等运算符” 我们应该这样称呼它们。总是。

标签: c# c#-9.0


【解决方案1】:

唯一的区别(除了语法)是,编译器保证在使用 is not null 而不是 != null(或 is null 而不是 == null)时不会调用用户重载的运算符。

【讨论】:

    【解决方案2】:

    e != nulle is not null 的主要区别在于编译器执行比较的方式。

    Microsoft: “编译器保证在计算表达式 x 为 null 时调用 no 用户重载的相等运算符 ==。”

    底线:如果您编写的代码不想依赖于某人对!=== 运算符的实现,请使用is nullis not null,因为它更安全。

    请看下面的例子:

    public class TestObject
    {
      public string Test { get; set; }
    
      // attempt to allow TestObject to be testable against a string
      public static bool operator ==(TestObject a, object b)
      {
        if(b == null)
          return false;
        
        if(b is string)
          return a.Test == (string)b;
    
        if(b is TestObject)
          return a.Test == ((TestObject)b).Test;
    
        return false;
      }
    
      public static bool operator !=(TestObject a, object b)
      {
        if(b == null)
          return false;
        
        if(b is string)
          return a.Test != (string)b;
    
        if(b is TestObject)
          return a.Test != ((TestObject)b).Test;
    
        return false;
      }
    }
    

    如果您的代码需要确保对象不为空,使用is not null 会比使用!= null 提供更好的结果,因为==/!= 运算符的重载有点奇怪。

    控制台示例 1:

    TestObject e = null;
    
    if(e == null)
      Console.WriteLine("e == null");
    
    if(e is null)
      Console.WriteLine("e is null");
    

    输出:e is null

    控制台示例 2:

    TestObject e = new TestObject();
    
    if(e != null)
      Console.WriteLine("e != null");
    
    if(e is not null)
      Console.WriteLine("e is not null");
    

    输出:e is not null

    重载运算符都没有“正确”实现,因此控制台永远不会输出e == nulle != null

    【讨论】:

      猜你喜欢
      • 2011-05-03
      • 2019-08-12
      • 1970-01-01
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多