日期:2014-05-17  浏览次数:21081 次

C#中的声明与定义
在《C#入门经典》第6章的一个例子:
int i; 
string text; 
for (i = 0; i < 10; i++) 

text = "Line " + Convert.ToString(i); 
Console.WriteLine("{0}", text); 

Console.WriteLine("Last text output in loop: {0}", text);


这段代码会失败,原因书上说是没有在变量使用前对其进行声明和初始化。

另外,在英文原著中的解释:

The explanation for this behavior is related to memory allocation for the text variable, and indeed any variable. Merely declaring a simple variable type doesn’t result in very much happening. It is only when values are assigned to the variables that values are allocated a place in memory to be stored. When this allocation takes place inside a loop, the value is essentially de?ned as a local value and goes out of scope outside of the loop.

意思是说比如:
int a;  这样只是声明,没有分配内存?
int a=1;  这样是定义,分配了内存?

回到上面的例子,
string text;
这一句只是声明了变量text,并没为之分配内存,而在下面的循环中,为text分配内存,但循环中的text作用域只在循环中,出了循环就失效了,是这个意思吗?
这跟C++好象不一样啊?
声明 定义

------解决方案--------------------
如果你细心点你会发现
string text;
            text = "Line";
            Console.WriteLine("Last text output in loop: {0}", text);
这种赋值没有错。之所以你那个会报错是因为,赋值操作在for循环里面。就好像我在for循环里面定义string aa;在for循环外面是无法访问的,也就是说你在for循环里面赋的值,编译无法访问,所以就不能通过编译。
------解决方案--------------------
和分配内存无关。

这么设计只是为了防呆。和C/C++不同,C#在语法上有很多防呆的设计。

这就好比USB反过来插不进去,不是因为它的金属端口不匹配——你把那个东西破坏了可以插进去,但是会烧坏电脑。

一样的道理,你定义一个变量而不初始化,C允许你这么做,但是这会导致程序出现潜在的bug。

C#的设计者干脆让编译器限制你这么写。