欢迎光临
我们一直在努力

C#高级编程阅读笔记一(关于值类型和引用类型)-.NET教程,C#语言

建站超值云服务器,限时71元/月

数据在内存中的存储位置,取决于它的数据类型,在c#中,分为值类型和引用类型,值类型的数据存储在内存中的堆栈中,每个变量或程序都有自己的堆栈,不可以共用一个堆栈地址。当数据一个值类型的变量传递到另一个相同类型的变量时,会在堆栈中分配两个不同的地址。

而引用类型的数据存储在内存中的堆中,可以不同的变量或程序共同使用同一个位置的数据。当数据从一个引用类型的变量传递到另一个相同类型的变量时,只是把这个变量的引用地址传递给新的变量,同时引用当前堆中存储的数据。

可以通过实例得到详细结论:

using system;

// 定义一个矩形类,类属于引用类型

class refrectangle

{

public int width;

public int height;

}

// 定义一个矩形结构,属于值类型

struct valrectangle

{

public int width;

public int height;

}

class refvalrectangle

{

public static void main()

{

// 创建一个矩形对象,并将值传递给另一个新对象.

refrectangle ref1 = new refrectangle(); ;

ref1.width = 3;

ref1.height = 4;

refrectangle ref3 = ref1;

console.writeline("dimensions of ref1 are : " + ref3.width.tostring() + "…" + ref3.height.tostring());

console.writeline("change dimensions of ref1");

ref1.width = 10;

ref1.height = 50;

bool btransfer = ref3.equals(ref1);

console.writeline("dimensions of ref1 now are : " + ref3.width.tostring() + "….." + ref3.height.tostring());

console.writeline(btransfer.tostring());

console.readline();

// 创建一个矩形结构,将值传递给一个新的矩形结构

valrectangle val1 = new valrectangle();

val1.width = 3;

val1.height = 4;

valrectangle val3 = val1;

console.writeline("dimensions of val1 are : " + val3.width.tostring() + "…" + val3.height.tostring());

console.writeline("change dimensions of val1");

val1.width = 10;

val1.height = 50;

bool bpass = val3.equals(val1);

console.writeline("dimensions of val1 now are : " + val3.width.tostring() + "….." + val3.height.tostring());

console.writeline(bpass.tostring());

console.readline();

}

}

可以看到,当值类型的变量传递后,改变第一个变量,不会影响第二个变量的值,这是因为,当变量传递时,是在堆栈中又分配了一个地址给新的变量,所以这个两个变量在传递发生后,不再有关系。

而引用类型的变量传递后,改变第一个,第二个变量随之改变,是因为两个变量同时引用堆中的一个地址的内容,当一个变量改变,对应与内存中的堆也随之改变,而另外的一个变量也随之改变。

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » C#高级编程阅读笔记一(关于值类型和引用类型)-.NET教程,C#语言
分享到: 更多 (0)