在 C# 中检查对象是否为空
本教程将讨论在 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
。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。