为什么if语句中的字符串初始化会阻止我打印?

mad*_*man 2 c# syntax if-statement language-design

我没有问题

{
    string nom;
    string ou;
    nom = "1";
    if (nom == "1")
    {
        nom +=1;
        ou = nom;
    }
    Console.Write(ou);
}
Run Code Online (Sandbox Code Playgroud)

但我不能打印你的价值我不知道为什么

Jed*_*oky 11

尝试这样的事情

{
    string nom;
    string ou = String.Empty;
    nom = "1";
    if (nom == "1")
    {
        nom +=1;
        ou = nom;
    }
    Console.Write(ou);
}
Run Code Online (Sandbox Code Playgroud)


Meh*_*ari 7

C#编译器要求在使用前明确初始化变量.

定义初始化是编译时的事情,它不考虑变量的运行时值.

但是,如果将变量nom明确定义为const,则编译器将确保它在运行时不会更改,并且if语句块将运行并且变量ou将被明确分配给.


tee*_*yay 6

这甚至可以编译吗?

nomstring- 你怎么办nom += 1

  • 字符串foo ="User id ="+ 10; 作品.结果是"用户ID = 10".在这里,nom将是"11".那可能不是预期的结果,诚然...... (4认同)

Mar*_*ijn 5

尝试用第二行替换

string ou = null;
Run Code Online (Sandbox Code Playgroud)

问题是如果nom不等于"1",则变量ou不会被初始化.这里的编译器希望保证为您分配了一个值.