c#字符串值类型与引用类型比较示例
classprogram
{
staticvoid main()
{
int a = 9; //给变量a赋值为9
int b = a; //将a的副本给变量b
b = 10;
console.writeline(string.format("a={0},b={1}", a, b));
person zs = newperson(); //张三
zs.age = 99; //张三的年龄是99
person sm = zs; //三毛等于张三,即张三和三毛就是同一个人
sm.age = 100; //三毛年龄变成100,张三也就变成了100
console.writeline(string.format("a={0},b={1}", zs.age, sm.age));
console.readkey();
}
}
classperson
{
publicint age { get; set; }
}
相同的结构,不同的结果。
证明string是引用类型
using system;
classprogram
{
staticvoid main()
{
int n = 99;
console.writeline("before:n={0}", n.gethashcode());
//此时获取到的哈希码值就是n的变量值
getint(n);
string s = "hello";
console.writeline("before:s={0}", s.gethashcode());
getstring(s);
console.readkey();
}
staticint getint(int n)
{
console.writeline("after:m={0}", n.gethashcode());
//传过来的是变量值,说明这是值传递
return n;
}
staticstring getstring(string s)
{
console.writeline("after:s={0}", s.gethashcode());
//传过来的是地址而不"hello",说明这时引用传递
return s;
}
}