§ ITPOW >> 文档 >> C#

C# 中判断 null

作者:vkvi 来源:ITPOW(原创) 日期:2008-1-3

判断字符串的长度是否为零可以用 if (str.Length == 0),但如果 str 可能是 null 引用(Basic 语言中为 Nothing),则直接这样用会产生异常,所以需要先判断是否为 null。

方法一、和 null 比较

if (str == null || str.Length == 0)

在 C++、C# 中,这里,如果 str == null 为 true,则不会继续判断 str.Length == 0,也就避免了异常的产生。

方法二、使用 string 的静态方法 IsNullOrEmpty

string.IsNullOrEmpty(string str)

这个方法是在 .NET Framework 2.0 中新增的,如果 str 为 null 引用或零长度字符串,则返回 true。

这个方法实际上相当于:

str == null || str.Length == 0

相关阅读

相关文章