随着C# 9.0的发布,引入了否定的空值常量模式。
模式匹配的文档说明如下:
从C# 9.0开始,您可以使用否定的空值常量模式来检查非空值,如以下示例所示:
除了语法之外,“e is not null”和“e != null”之间是否有任何区别?
if (e is not null) { // ... }
e != null
和e is not null
之间的主要区别在于编译器执行比较的方式。Microsoft: "当评估表达式x是否为null时,编译器保证不会调用任何用户重载的等号运算符==。"
底线:如果您正在编写不希望依赖于某人的!=
和==
运算符实现的代码,请使用is null
和is 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
与 TestObject
搭配会比使用 != null
更好,因为==
/!=
运算符的重载有点奇怪。
控制台示例1:
TestObject e = null;
if(e == null)
Console.WriteLine("e == null");
if(e is null)
Console.WriteLine("e is null");
输出:e 为空
控制台示例2:
TestObject e = new TestObject();
if(e != null)
Console.WriteLine("e != null");
if(e is not null)
Console.WriteLine("e is not null");
输出:e 不为 null
由于没有正确实现任何重载运算符,因此控制台从不输出 e == null
或 e != null
。
x is null
或x is not null
,它会发出错误:CS0037: Cannot convert null to '<your type>' because it is a non-nullable value type,但它会让你使用x == null
或x != null
(带有警告-* CS0472: The result of the expression is always 'false' since a value of type '<your type>' is never equal to 'null'*)。 - Zohar Peledstructs
是一个特殊情况,无法使用 is null
和 is not null
模式。但这不是问题所在。如果 OP 因 is not null
而出现错误,则问题将会是另外一个。然而,如果您希望的话,您可以编辑我的答案并添加此特殊情况作为信息。 - mamen
(object)e!= null
,以确保不涉及任何烦人的重载相等运算符。 - TheGeneral