值类型与引用类型的区别

1、概念讲解:

一、值类型:
ui

包括:sbyte、short、int、long、float、double、decimal(以上值类型有符号)spa

   byte、ushort、uint、ulong(以上值类型无符号)code

   bool、char对象

二、引用类型:
blog

包括:对象类型、动态类型、字符串类型内存

2、具体区别:

一、值类型:ci

byte b1 = 1; byte b2 = b1; Console.WriteLine("{0},{1}。", b1, b2); b2 = 2; Console.WriteLine("{0},{1}。", b1, b2); Console.ReadKey();

解释:字符串

byte b1 = 1;声明b1时,在栈内开辟一个内存空间保存b1的值1。string

byte b2 = b1;声明b2时,在栈内开辟一个内存空间保存b1赋给b2的值1。it

Console.WriteLine("{0},{1}。", b1, b2);输出结果为1,1。

b2 = 2;将b2在栈中保存的值1改成2。

Console.WriteLine("{0},{1}。", b1, b2);输出结果为1,2。

二、引用类型:

string[] str1 = new string[] { "a", "b", "c" }; string[] str2 = str1; for (int i = 0; i < str1.Length; i++) { Console.Write(str1[i] + " "); } Console.WriteLine(); for (int i = 0; i < str2.Length; i++) { Console.Write(str2[i] + " "); } Console.WriteLine(); str2[2] = "d"; for (int i = 0; i < str1.Length; i++) { Console.Write(str1[i] + " "); } Console.WriteLine(); for (int i = 0; i < str2.Length; i++) { Console.Write(str2[i] + " "); } Console.ReadKey();

解释:

string[] str1 = new string[] { "a", "b", "c" };声明str1时,首先在堆中开辟一个内存空间保存str1的值(假设:0a001),而后在栈中开辟一个内存空间保存0a001地址

string[] str2 = str1;声明str2时,在栈中开辟一个内存空间保存str1赋给str2的地址

for (int i = 0; i < str1.Length; i++)

{

  Console.Write(str1[i] + " ");

}

Console.WriteLine();

for (int i = 0; i < str2.Length; i++)

{

  Console.Write(str2[i] + " ");

}

Console.WriteLine();

输出结果为:

a b c

a b c

str2[2] = "d";修改值是修改0a001的值

for (int i = 0; i < str1.Length; i++)

{

  Console.Write(str1[i] + " ");

}

Console.WriteLine();

for (int i = 0; i < str2.Length; i++)

{

  Console.Write(str2[i] + " ");

}

输出结果为:

a b d

a b d

三、string类型:(特殊)

string str1 = "abc"; string str2 = str1; Console.WriteLine("{0},{1}。", str1, str2); str2 = "abd"; Console.WriteLine("{0},{1}。", str1, str2); Console.ReadKey();

解释:

string str1 = "abc";声明str1时,首先在堆中开辟一个内存空间保存str1的值(假设:0a001),而后在栈中开辟一个内存空间保存0a001地址

string str2 = str1;声明str2时,首先在堆中开辟一个内存空间保存str1赋给str2的值(假设:0a002),而后在栈中开辟一个内存空间保存0a002的地址

Console.WriteLine("{0},{1}。", str1, str2);输出结果为:
abc
abc

str2 = "abd";修改str2时,在堆中开辟一个内存空间保存修改后的值(假设:0a003),而后在栈中修改str2地址为0a003地址

Console.WriteLine("{0},{1}。", str1, str2);输出结果为:
abc
abd

堆中内存空间0a002将被垃圾回收利用。

 

以上是我对值类型与引用类型的理解,但愿能够给须要的朋友带来帮助。

相关文章
相关标签/搜索