更简单的写空或空的方式?

我确定我错过了一些东西。 对于某个项目,我需要检查字符串是空还是空。

有没有更简单的方法来写这个?

if(myString == "" || myString == null) { ... 

是的,已经存在String.IsNullOrEmpty辅助方法:

 if (String.IsNullOrEmpty(myString)) { ... } 
 if (string.IsNullOrEmpty(myString)) { ... } 

或者你可以利用扩展方法中的一个怪癖,它们允许为null:

 static class Extensions { public static bool IsEmpty(this string s) { return string.IsNullOrEmpty(s); } } 

然后让你写:

 if (myString.IsEmpty()) { ... } 

虽然您可能应该选择另一个名称而不是“空”。

如果您使用的是.NET 4,则可以使用

 if(string.IsNullOrWhiteSpace(myString)){ } 

其他:

 if(string.IsNullOrEmpty(myString)){ } 

为了避免空检查你可以使用?? 运营商。

 var result = value ?? ""; 

我经常使用它作为警卫,以避免发送我不想要的方法数据。

 JoinStrings(value1 ?? "", value2 ?? "") 

它还可用于避免不必要的格式化。

 string ToString() { return "[" + (value1 ?? 0.0) + ", " + (value2 ?? 0.0) + "]"; } 

这也可以在if语句中使用,它不是那么好但有时可以很方便。

 if (value ?? "" != "") // Not the best example. { } 

//如果字符串未定义为null,则IsNullOrEmpty可以很好地工作但是如果string定义为null,则trim将抛出exception。

 if(string.IsNullOrEmpty(myString.Trim()){ ... } 

//你可以使用IsNullOrWhiteSpace ,它可以很好地用于字符串中的多个空格.ie它对于多个空格也返回true

  if(string.IsNullOrWhiteSpace (myString.Trim()){ ... }