HOWTO · Csharp
在 C# 中检查对象是否为空
在 C# 中,有两种主要方法可用于检查对象是否为 null:==运算符和 is 运算符。
本教程将讨论在 C# 中检查对象是否为空的方法。
在 C# 中使用 == 运算符检查空对象
C# 中的二进制运算符 == 可以检查运算符左边的值是否等于运算符右边的值。以下代码示例向我们展示了如何使用 C# 中的 == 运算符检查对象是否为空。
using System;
namespace check_null_object {
class Program {
static void Main(string[] args) {
string check = null;
if (check == null) {
Console.WriteLine("check is null");
} else {
Console.WriteLine("check is not null");
}
}
}
}
输出:
check is null
上面的代码使用 C# 中的 == 二进制运算符检查字符串变量 check 是否为 null。
在 C# 中使用 is 关键字检查空对象
我们还可以使用 is 关键字在 C# 中检查对象是否为空。在 C# 中,is 关键字可以用作二进制运算符 == 的替代。以下代码示例向我们展示了如何使用 C# 中的 is 关键字确定对象是否为空。
using System;
namespace check_null_object {
class Program {
static void Main(string[] args) {
string check = null;
if (check is null) {
Console.WriteLine("check is null");
} else {
Console.WriteLine("check is not null");
}
}
}
}
输出:
check is null
上面的代码使用 C# 中的 == 二进制运算符检查字符串变量 check 是否为 null。