“IsNullOrWhiteSpace”的反义词是什么?

问题描述 投票:0回答:2

我使用带有“IsNullOrWhiteSpace(+textbox)”的 if 条件来引用没有值或只有空格的文本字段。但是,现在我需要知道热指定一个不为空或仅空格的字段。

这是我写的代码:

if (string.IsNullOrWhiteSpace(pathofsrcfilesTOCOPY.Text))

但是,如果我想指定仅在文本字段不为空或为空时运行命令怎么办?

c#
2个回答
7
投票
如果文本为空或空格,则

string.IsNullOrWhiteSpace
返回 true。如果返回值为
false
,则文本将使用非空白字符填充。

使用

!
搜索条件不成立的位置。

if (!string.IsNullOrWhiteSpace(pathofsrcfilesTOCOPY.Text))

这相当于:

if (string.IsNullOrWhiteSpace(pathofsrcfilesTOCOPY.Text) == false)

如果

pathofsrcfilesTOCOPY.Text
填充有非空白文本,以上两者都会进入 if 语句。


2
投票

值得注意的是,虽然接受的答案是正确的,但我发现在将其结果分配给变量然后在 if 条件下评估该变量时更容易遵循。

bool isPathEmpty = string.IsNullOrWhiteSpace(pathofsrcfilesTOCOPY.Text);
if (!isPathEmpty) 
{
    //...
}
© www.soinside.com 2019 - 2024. All rights reserved.