如何检查String是否为null

我想知道是否有一个特殊的方法/技巧来检查String对象是否为null。 我知道String.IsNullOrEmpty方法但我想区分null String和空String(= "" )。

我应该简单地使用:

 if (s == null) { // blah blah... } 

……还是有另一种方式?

对象不能为null – 表达式的值可以为null。 值得在你的脑海中清楚地发挥作用。 s的值不是对象 – 它是引用 ,它是null或引用对象。

是的,你应该使用

 if (s == null) 

请注意,这仍将使用在字符串中定义的重载==运算符,但这将做正确的事情。

您可以使用空合并双重问号来测试字符串或其他可空值类型中的空值:

 textBox1.Text = s ?? "Is null"; 

运营商 ‘??’ 询问’s’的值是否为null,如果不是则返回’s’; 如果为null,则返回运算符右侧的值。

更多信息: https : //msdn.microsoft.com/en-us/library/ms173224.aspx

还值得注意的是有一个零条件运算符? 和?[在VS2015的C#6.0(和VB)中引入

 textBox1.Text = customer?.orders?[0].description ?? "n/a"; 

如果description为null,或者如果订单为null,或者customer为null,则返回“n / a”,否则返回description的值。

更多信息: https : //msdn.microsoft.com/en-us/library/dn986595.aspx

可以肯定的是,你应该使用函数来检查null和empty,如下所示:

 string str = ... if (!String.IsNullOrEmpty(str)) { ... } 

您可以在下面的评论中查看null或Number。

首先,您可以在ypur应用程序中添加引用“Microsoft.VisualBasic”。

bool b = Microsoft.VisualBasic.Information.IsNumeric(“null”); bool c = Microsoft.VisualBasic.Information.IsNumeric(“abc”);

在上面,b和c应该是假的。

我希望这可以帮助你。