在选择之外使用声明的变量(IF) [英] Using Declared Variable Outside A Selection (IF)
本文介绍了在选择之外使用声明的变量(IF)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨
基本上我有一个if循环选择,并且我已经在其中定义了一个变量,但是在其他地方我也希望使用它,但我不能有人有请给我任何建议。
Hi
Basically i have a if loop selection, and i have defined a variable in it, however in the else i wish to use it aswell, but i cant does anyone have any suggestions how i can do this please.
if (Selection)
{
String Name = "Hello";
}
Else
{
Name;
}
以上就是我想要发生的事情,不要让我使用变量Name建议请。
Above is what i wish to happen something like that bu it wont let me use the variable "Name" any suggestions please.
推荐答案
String Name = string.Empty;
if (Selection)
{
Name = "Hello";
}
Else
{
Name = "Another value";
}
只需在if块之外声明你的varable。
Just declare your varable outside of if block.
String Name;
if (Selection)
{
Name = "Hello";
}
else
{
Name="Something else";
}
唯一的问题是定义的位置:你的名称
的声明是只能在其区块范围内访问。如果您不使用大括号,即使声明也会导致编译错误。分辨率看起来像
The only problem is the locality of definition: your declaration ofName
is accessible only in its block's scope. If you didn't use curly brackets, even the declaration would cause compilation error. The resolution would look like
string name = null; // or something else, but some initialization is absolutely required
if (Selection)
name = "Hello";
else
name = "something else";
在进一步移动之前,您需要阅读地点和范围主题。几乎任何C#手册都包括这个主题。
祝你好运,
这篇关于在选择之外使用声明的变量(IF)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文