部分摘自《C# 7.0 核心技术指南》。
数据类型
C#中的数据类型分为值类型 (Value type) 和引用类型(reference type)
1 值类型和引用类型
-
值类型
所有的值类型都集成自 System.ValueType 上,除非加声明?
否则不可为null
,保存在堆栈(Stack,先进后出)上,常见的值类型有:整形、浮点型、bool
、枚举(enum)、结构体(struct)等。 -
引用类型
所有的引用类型都继承自 System.Object 上,引用类型保存在托管堆(Head,先进先出)上,常见的类型有:数组、字符串、接口、委托、object 等。比如,创建一个对象Student stu; stu = new Student();
首先声明了一个
Student
的引用stu
,在堆栈上给这个引用分配存储空间,但这只是一个引用,而不是实际的Student
对象。stu
引用包含了存储Student
对象的地址,需要 4 个字节把 0~4GB 之间的地址存储为一个整数,因此stu
占 4 个字节。
第 2 行代码首先分配托管堆上的内存,用来存储Student
实例,然后把变量stu
的值设置为分配给Student
对象的内存地址。 -
C# 预定义类型
- 值类型
- 数值
- 有符号整数(
sbyte
、short
、int
、long
) - 无符号整数(
byte
、ushort
、uint
、ulong
) - 实数(
float
、double
、decimal
)
- 有符号整数(
- 逻辑值(
bool
) - 字符(
char
)
- 数值
- 引用类型
- 字符串(
string
) - 对象(
object
)
- 字符串(
- 值类型
2 数据赋值
-
值类型赋值
class Progarm { static void Main() { Point p1 = new Point(); p1.x = 7; Point p2 = p1; Console.WriteLine(p1.x); // 7 Console.WriteLine(p2.x); // 7 p1.x = 9; Console.WriteLine(p1.x); // 9 Console.WriteLine(p2.x); // 7 } } //定义Point结构体 public struct Point { public int x; public int y; }
-
引用类型赋值
class Progarm { static void Main() { Point p1 = new Point(); p1.x = 7; Point p2 = p1; Console.WriteLine(p1.x); // 7 Console.WriteLine(p2.x); // 7 p1.x = 9; Console.WriteLine(p1.x); // 9 Console.WriteLine(p2.x); // 9 } } // 定义 Point 类 public class Point { public int x; public int y; }
🍀 数组赋值时,如:
int[] arr1 = {0, 0, 0, 0};
int[] arr2 = arr1;
在这里 arr1
是数组 {0, 0, 0, 0}
的引用,这里将 arr1
赋值给 arr2
,实际上 arr2
引用的也是数组 {0, 0, 0, 0}
,如果 arr1
对数组操作,arr2
也会产生相应的变化,如:
arr1[1] = 1;
那么此时 arr2 = {0, 1, 0, 0}
。