有没有办法解决.IsNullOrEmpty()和.Trim()的双重If语句?(里面有更多细节)

fly*_*227 0 c# c#-4.0

所以假设你有一个字符串,你想要检查null/empty.您还想检查空字符串.我知道如何执行此操作(下面)的唯一方法是首先检查null并然后检查空字符串.如果在检查null之前执行.Trim(),并且存在null,则表示您有错误.

我真的不喜欢使用两个单独的If语句.有没有解决的办法?

例:

if(!string.IsNullOrEmpty(strMyVariable)
{
   if(!string.IsNullOrEmpty(strMyVariable.Trim()))
   {
      //the variable is not null, empty, or contain an empty string
      //so you can now (finally!) do something with it.
   }
}
Run Code Online (Sandbox Code Playgroud)

Yac*_*sad 7

你可以IsNullOrWhiteSpace像这样使用:

if (!string.IsNullOrWhiteSpace(strMyVariable))
{

}
Run Code Online (Sandbox Code Playgroud)

引用MSDN参考:

指示指定的字符串是空,空还是仅包含空格字符.