如何使用引用類型來改變變量的值
作者:佚名 時間:2013-11-07 分享到:
引用類型總是從托管堆上分配,c#的new操作符返回的就是對象位于托管堆中的內存地址-這個內存地址指向對象占用的數據位,將一個引用類型的實例賦值給另一個引用類型的實例就是將這個實例的指針賦給另一個實例,,也就是說賦值后兩個實例指向同一個內存塊,改變一具實例的值自然就改變另外一個實例的內容.
先定義一下類,代碼如下:
class hello
{
private string hellotxt;
public string hellotxt;
{
get { return this.hellotxt; }
get { this.hellotxt = value; }
}
pubile hello(string text)
{
hellotxt = text;
}
}
然后使用這個類,代碼如下:
hello hello1 = new hello("hello world!");
hello hello2 = hello1;
hello1.hellotxt = "hello";
console,writeline(hello.hellotxt); //hello
大家通過上面代碼的演示就可以看到改變了hello1的屬性之后,hello2的屬性也自動變了.
如沒特殊注明,文章均為上海聯楷網絡原創,轉載請注明來自:http://www.ktcbnqb.cn/help/20151126/n1658.html