首页蓝耳朵|小小蓝耳朵广州图书馆外文室英语儿童读物资源介绍网佛教青年之友旧版收集永硕E盘Phonics Short Vowels Game 
关于null和""
所属栏目:ASP.NET(webform)  时间:2009-04-13 09:10  作者:狼子

截自《Essential C# 2.0》P49

 It is important to note that assigning the value null to a referenct type is distinct from not assigning it at all. In other words, a variable that has been assigned null has still been set, and a variable with no assignment has not been set and therefore will often cause a compile error if used prior to assignment.
 Assigning the value null to a string is distinctly different from assigning an empty string, "". null indicates that the variable has no value. "" indicates that there is a value: an empty string.

一直觉得奇怪,为什么下面三种情况下的第二种是正确的。。。

第一种情况:
string a;
Response.Write(a);
这样子肯定是错的,编译也不会通过:使用了未赋值的局部变量“a”

 

第二种情况:
string a = null;
Response.Write(a);
这样子是对的,就是,为什么是对的呢?

 

第三种情况
string a = "";
Response.Write(a);
这样子肯定是对的

 

以前明白string a = "";的时候为什么对,不明白为什么设置成null也会对,因为null是什么东西都没有啊,现在看这两段话就明白了

string a;
这个只是声明了一个string变量a,没有分配内存空间

string a = null;
这个声明了一个string变量a,还分配了一个内存空间给他,让他用来保存以后赋值给他的字符串的起始地址,就是,现在这个内存空间里还没有保存任何数据

string a = "";
这个声明了一个string变量,还分配了一个内存空间,这个空间里,保存着一个地址,这个地址指向内存中另一个内存块,这个内存块里,保存着""

因为字符串是不可以被修改的,所以如果把另一个字符串赋值给同一个字符串变量,只是把另一个字符串的起始地址放到了这个字符串变量指向的内存空间里

小楼宝宝的涂鸦花花(Imitater)的博客起名称骨测字皖ICP备06000023号-17