我使用带有“IsNullOrWhiteSpace(+textbox)”的 if 条件来引用没有值或只有空格的文本字段。但是,现在我需要知道热指定一个不为空或仅空格的字段。
这是我写的代码:
if (string.IsNullOrWhiteSpace(pathofsrcfilesTOCOPY.Text))
但是,如果我想指定仅在文本字段不为空或为空时运行命令怎么办?
string.IsNullOrWhiteSpace
返回 true。如果返回值为 false
,则文本将使用非空白字符填充。
使用
!
搜索条件不成立的位置。
if (!string.IsNullOrWhiteSpace(pathofsrcfilesTOCOPY.Text))
这相当于:
if (string.IsNullOrWhiteSpace(pathofsrcfilesTOCOPY.Text) == false)
如果
pathofsrcfilesTOCOPY.Text
填充有非空白文本,以上两者都会进入 if 语句。
值得注意的是,虽然接受的答案是正确的,但我发现在将其结果分配给变量然后在 if 条件下评估该变量时更容易遵循。
bool isPathEmpty = string.IsNullOrWhiteSpace(pathofsrcfilesTOCOPY.Text);
if (!isPathEmpty)
{
//...
}