C# 空文本框被视为空字符串还是 null?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16612057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:28:05  来源:igfitidea点击:

Is an empty textbox considered an empty string or null?

c#asp.net.netnull

提问by Rex_C

The text box in question is involved in an if statement within my code, something to the effect of

有问题的文本框包含在我的代码中的 if 语句中,其效果是

if (textbox.text != "") 
{
    do this
}

I am curious if an empty text box will be considered an empty string or a null statement.

我很好奇空文本框是否会被视为空字符串或空语句。

采纳答案by PSL

Try to use IsNullOrWhiteSpace, this will make sure of validating the whitespace too without having to trim it.

尝试使用IsNullOrWhiteSpace,这将确保验证空白也无需修剪它。

if (!string.IsNullOrWhiteSpace(textbox.Text))
{
    //code here
}

According to documentation string.IsNullOrWhiteSpaceevaluates to:

根据文档string.IsNullOrWhiteSpace评估为:

return String.IsNullOrEmpty(value) || value.Trim().Length == 0;

String.IsNullOrWhiteSpace:

String.IsNullOrWhiteSpace

Indicates whether a specified string is null, empty, or consists only of white-space characters.

指示指定的字符串是否为空、空或仅由空白字符组成。

回答by DCNYAM

It will be considered an empty string.

它将被视为一个空字符串。

回答by Sachin

It will be an empty string but better to check with this IsNullOrEmptyor IsNullOrWhiteSpace

它将是一个空字符串,但最好使用此IsNullOrEmptyIsNullOrWhiteSpace进行检查

if (!string.IsNullOrEmpty(textbox.text))
{
  //do this
}

IsNullOrWhiteSpaceis also take care of whitespace in input string. So if you don't want to execute the code for whitespace too then use second option.

IsNullOrWhiteSpace也处理输入字符串中的空格。因此,如果您也不想为空格执行代码,请使用第二个选项。

回答by Darren

In short it will be an empty string, but you could use the debugger and check that yourself.

简而言之,它将是一个空字符串,但您可以使用调试器并自行检查。

However for best practice use IsNullOrEmptyor IsNullOrWhiteSpace

但是对于最佳实践使用IsNullOrEmptyIsNullOrWhiteSpace

if (!string.IsNullOrEmpty(textbox.Text)) {

}

Alternatively:

或者:

if (!string.IsNullOrWhiteSpace(textbox.Text)) {

}    

http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx

http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx

回答by Bip

if (textbox.text != "" || textbox.text != null)

if (textbox.text != "" || textbox.text != null)

回答by Rishi

string search = txtSearch.Text.Trim() != "" ? txtSearch.Text.Trim() : "0";