日期:2014-05-17 浏览次数:21036 次
int a1 = 10; StringBuilder strb1 = new StringBuilder("ABC"); int a2 = a1; StringBuilder strb2 = strb1; bool bl1 = object.ReferenceEquals(a1,a2); //false为值类型(因为值类型要装箱) bool bl2 = object.ReferenceEquals(strb1,strb2); //true为引用类型
private void button2_Click(object sender, System.EventArgs e) { StringBuilder strb1 = new StringBuilder(); StringBuilder strb2 = new StringBuilder(); Test1(strb1); Test2(ref strb2); string str1 = strb1.ToString(); //str1值:"A" string str2 = strb2.ToString(); //str2值:"BC" } void Test1(StringBuilder strb) { //strb和strb1是两个栈中对象,但指向相同的地址,这个操作是改变堆中对象 strb.Append("A"); //这里将strb指向一个新的堆中对象,所以后面的操作与strb1指向的栈中对象无关 strb = new StringBuilder("B"); strb.Append("C"); } void Test2(ref StringBuilder strb) { //这里的strb和strb2是同一个栈中对象,所以改变strb的值使其指向另一个对象也等于改变strb2 strb = new StringBuilder("B"); strb.Append("C"); }