Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#Strings-为什么null给我的结果与“C”不同&引用;?_C#_String_Null - Fatal编程技术网

C#Strings-为什么null给我的结果与“C”不同&引用;?

C#Strings-为什么null给我的结果与“C”不同&引用;?,c#,string,null,C#,String,Null,我有两张表格。在第一种形式中,我有以下代码 frm_BL addBranch = new frm_BL(); do { addBranch.ShowDialog(); if (addBranch.txtAmount.Text == "") { break; } } while (true); 以主要形式。这就是第二种形式 private void btnAccept_Click(object sender, EventArgs e) {

我有两张表格。在第一种形式中,我有以下代码

frm_BL addBranch = new frm_BL();

do
{
    addBranch.ShowDialog();
    if (addBranch.txtAmount.Text == "")
    {
        break;
    }

} while (true);
以主要形式。这就是第二种形式

private void btnAccept_Click(object sender, EventArgs e)
{
    this.Close();
}
但是,我发现如果我将主窗体的代码更改为:

 if (addBranch.txtAmount.Text == null) //changed to null
第二种形式不断出现。但如果它停留在

if (addBranch.txtAmount.Text == "") 

它关闭窗体。有人能解释这是为什么吗

A
null
String
不同于空的
字符串
。请改用
String.Empty()

空字符串和空字符串是两件不同的事情,如果要处理这两种情况,可以改用String.IsNullOrEmpty

null表示对字符串的引用不存在(指向nothing)


空字符串表示对不包含任何内容的字符串的引用(例如指向空字符数组的指针)。

最好的方法是:

if (String.IsNullOrEmpty(addBranch.txtAmount.Text))
txtAmount.Text
属性是包含文本框内容的
字符串。如果文本框为空,则为零长度字符串

检查是否与
null
相等表示“如果文本框没有字符串…”,这将始终为false。要检查的正确条件是“如果文本框的字符串为空…”

使用
IsNullOrEmpty
方法检查这两种情况。在这种情况下,字符串永远不应该为null,但检查也无妨


请注意,
是一个空字符串(相当于
string.empty
),而
null
表示该字符串不存在。

我将查看定义以了解更多信息:

null关键字是表示null引用的文本,该引用不引用任何对象。null是引用类型变量的默认值。普通值类型不能为null。但是,C#2.0引入了可空值类型

此字段的值(String.Empty)是长度为零的字符串“”。在应用程序代码中,此字段最常用于将字符串变量初始化为空字符串的赋值

我们看到的另一件事是“要测试字符串的值是Nothing还是string.Empty,请使用IsNullOrEmpty方法。”


因此,当某个内容为
null
时,它表示对nothing的引用(最常见的是引用0),而当字符串包含null值时,这意味着该字符串为空,但它包含对有效内存的引用。

txtAmount.Text永远不会返回null,无论您编写代码是什么(在c中)还是对于每个有效(非null)文本框)


TextBox.Text返回一个空字符串或非空字符串。

除了已经正确的答案之外,我还将在检查中添加Trim(),因为在大多数情况下,只有空格的字符串是不可接受的,尤其是对于TextBox输入

if (string.IsNullOrEmpty(addBranch.txtAmount.Text.Trim())) 

哇,这是一个很好的答案。谢谢