string s1 = "hello";
string s2 = s1;
Console.WriteLine(s1);
Console.WriteLine(s2);
s1 = "world";
Console.WriteLine(s1);
Console.WriteLine(s2);
string s2 = s1;
Console.WriteLine(s1);
Console.WriteLine(s2);
s1 = "world";
Console.WriteLine(s1);
Console.WriteLine(s2);
代码输出为:
hello
hello
world
hello
C#高级编程中是这么解释的,s1被修改后,会重新分配一块内存,来指向新的s1。这是解释了为什么会有这个结果。但是,它没有解释,CLR为什么要这么特殊处理string类。难道,因为string类用的特别多,要符合大家的使用习惯?
看下面这段代码,class很明显也是一个reference,但是结果却和上面不同。
// 类的定义
public class Test{
private int number;
public Test(int number){
this.number = number;
}
public int Number{
get{return number;}}
set{number = value;}
}
public override string ToString(){
return Number.ToString();
}
}
// 测试代码
Test t1 = new Test(10);
Test t2 = t1;
Console.WriteLine(t1.ToString());
Console.WriteLine(t2.ToString());
t1.Number = 20;
Console.WriteLine(t1.ToString());
Console.WriteLine(t2.ToString());
public class Test{
private int number;
public Test(int number){
this.number = number;
}
public int Number{
get{return number;}}
set{number = value;}
}
public override string ToString(){
return Number.ToString();
}
}
// 测试代码
Test t1 = new Test(10);
Test t2 = t1;
Console.WriteLine(t1.ToString());
Console.WriteLine(t2.ToString());
t1.Number = 20;
Console.WriteLine(t1.ToString());
Console.WriteLine(t2.ToString());
上述代码输出的,是我们期望的值:
10
10
20
20