【发布时间】:2014-09-20 06:39:11
【问题描述】:
我是 C# 新手,在变量范围方面遇到了一些问题。
if(number > 10)
{
int someNr = 5;
}
else
{
/* .... */
}
if(number2 < 50)
{
someNr = 10; /* PRODUCES AN ERROR */
}
else
{
/* ........ */
}
我知道如果 number 不 > 10,那么 someNr 将不会被声明为 int。但是我应该写两次 int someNr 吗?如果if 都是真的呢?双重申报?我应该在if 之外声明变量吗?
类变量
PHP
class TEST {
private $test = 'test';
private function testVariable(){
/* Not declared */
echo $test;
}
private function testVariable2(){
/* echo 'test' */
echo $this->test;
}
}
C#
class TEST {
private string test = "test";
private void testVariable(){
/* takes the value of class variable test */
test;
}
private function testVariable2(){
/* takes also the value of class variable 'test' */
this.test;
}
}
如果
C#
class TEST {
private string test = "test";
private void testVariable(){
string test = "somethingOther";
Console.WriteLine(test);
}
}
test 是“test”还是“somethingOther”?
哪个优先?类变量还是局部方法变量?
【问题讨论】:
-
为什么不用一些简单的代码来测试一下呢?会比等待答案更快...
-
我会这样做,但我相信我会通过一些答案获得额外的知识!
-
很明显,在 Visual Studio 中花 2 秒“运行”会给出答案,所以是的,是的。
-
@developerwjk:如果对 OP 来说很明显,那么这个问题就不会被问到。每个人都曾经是初学者,包括你。有一天你不知道这个问题的答案,然后第二天你知道了;今天是 OP 的那一天。
-
@developerwjk:您在上一条评论中的逻辑是错误的。编译语言和需要声明存储的语言之间没有逻辑联系。您可以使用需要声明的解释型语言和不需要声明的编译型语言。