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

发布于 2024-07-13 18:13:32 字数 214 浏览 7 评论 0原文

我对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

泛泛之交 2024-07-20 18:13:32

尝试这样的事情

{
    string nom;
    string ou = String.Empty;
    nom = "1";
    if (nom == "1")
    {
        nom +=1;
        ou = nom;
    }
    Console.Write(ou);
}

Try something like this

{
    string nom;
    string ou = String.Empty;
    nom = "1";
    if (nom == "1")
    {
        nom +=1;
        ou = nom;
    }
    Console.Write(ou);
}
云淡风轻 2024-07-20 18:13:32

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 as const, the compiler would be sure that it would not change at runtime and the if statement block would run and the variable ou would be definitely assigned to.

一影成城 2024-07-20 18:13:32

这甚至可以编译吗?

nom 是一个字符串 - 你怎么能做到nom += 1

Does this even compile?

nom is a string - how can you do nom += 1?

绅士风度i 2024-07-20 18:13:32

尝试将第二行替换为

string ou = null;

问题是,如果 nom 结果不等于“1”,则变量 ou 将不会被初始化。 这里编译器想要保证ou已经被赋值了。

Try replacing the second line with

string ou = null;

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.

洋洋洒洒 2024-07-20 18:13:32

这是因为 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.

愿得七秒忆 2024-07-20 18:13:32

该代码片段甚至无法编译,更不用说打印ou了。 C# 强制所有变量在访问之前进行初始化,但在您的情况下并不总是如此。 因此改为

string ou;

说:

string ou = "";

就可以了。

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 changing

string ou;

to, say:

string ou = "";

will do just fine.

送君千里 2024-07-20 18:13:32

另一种选择是在 else 中设置 ou:

if (nom == "1")
{
    nom +=1;
    ou = nom;
} else 
{
    ou = "blank value";
}

Another option is to set ou in an else:

if (nom == "1")
{
    nom +=1;
    ou = nom;
} else 
{
    ou = "blank value";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文