为什么 if 语句中的字符串初始化会阻止我打印?
我对 if 没有什么问题,
{
string nom;
string ou;
nom = "1";
if (nom == "1")
{
nom +=1;
ou = nom;
}
Console.Write(ou);
}
但我无法打印 ou 值,我不知道为什么
i have little problem with if
{
string nom;
string ou;
nom = "1";
if (nom == "1")
{
nom +=1;
ou = nom;
}
Console.Write(ou);
}
but i cant print ou value i dont know why
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
尝试这样的事情
Try something like this
C#编译器要求变量在使用前必须明确初始化。
明确的初始化是编译时的事情,它不考虑变量的运行时值。
但是,如果变量
nom
显式定义为const
,编译器将确保它在运行时不会更改,并且if
语句块将运行并且变量ou
将被明确分配。C# compiler requires the variables to be definitely initialized before use.
Definite initialization is a compile-time thing, it doesn't consider runtime values of variables.
However, if the variable
nom
was explicitly definied asconst
, the compiler would be sure that it would not change at runtime and theif
statement block would run and the variableou
would be definitely assigned to.这甚至可以编译吗?
nom
是一个字符串
- 你怎么能做到nom += 1
?Does this even compile?
nom
is astring
- how can you donom += 1
?尝试将第二行替换为
问题是,如果 nom 结果不等于“1”,则变量 ou 将不会被初始化。 这里编译器想要保证ou已经被赋值了。
Try replacing the second line with
The problem is that if nom turns out not to equal "1", the variable ou won't have been initialized. The compiler here wants to guarantee that ou has been assigned a value.
这是因为 ou 在 if 块的范围之外未分配。 将声明行更改为 string ou = string.Empty; ,它应该可以工作。
This is because ou is unassigned outside the scope of the if block. Change the declaration line to
string ou = string.Empty;
and it shoudl work.该代码片段甚至无法编译,更不用说打印
ou
了。 C# 强制所有变量在访问之前进行初始化,但在您的情况下并不总是如此。 因此改为说:
就可以了。
This snippet won't even compile, let alone printing
ou
. C# enforces all variables to be initialized before accessing, which is not always true in your case. Thus changingto, say:
will do just fine.
另一种选择是在 else 中设置 ou:
Another option is to set ou in an else: