求助:关于引用类型和值类型:(在线等)
class MyClass
{
public int Val;
}
class Program
{
static void Main(string[] args)
{
MyClass Myobject = new MyClass();
MyClass Myobject2 = Myobject;
Myobject.Val = 43;
Myobject2.Val = Myobject.Val;
Console.WriteLine( "{0} ",Myobject.Val); //43
Console.WriteLine( "{0} ",Myobject2.Val);//43
Myobject.Val = 77;
Console.WriteLine( "{0} ", Myobject.Val);//77
Console.WriteLine( "{0} ", Myobject2.Val);//77
string s1 = "abc ";
string s2 = s1;
Console.WriteLine( "{0} ", s1);//abc
Console.WriteLine( "{0} ", s2);//abc
s1 = "def ";
Console.WriteLine( "{0} ", s1);//def
Console.WriteLine( "{0} ", s2);//abc ???
}
}
string也属于引用类型,为什么s2的结果还是abc而不是def?
------解决方案--------------------string是引用类型,但是为了保持与以前的编程语言语法的一致性,当 s1 = "def ";时,实际上是新建了一个字符串,所以引用地址发生了变化.java中也是这样处理的。楼主看stringbuilder类会有更深的体会。
------解决方案--------------------string类是引用类型..
不过每一个字符串都是一个字符串实例,也就是说 "abc "和 "def "都是一个新的字符串实例,当s1指向 "def "的时候,s2还是指向 "abc "的