基元类型,引用类型与值类型
1.基元类型
基元类型:编译器直接支持的概念称作基元类型
简单来说,就是int,char,bool这些基本类型,基元类型会直接映射到Framework类库(FCL)中的类型,
如int会映射到System.Int32类型,所以,
int a=0;
System.Int32 b=0;
两者等价,都会编译生成成相同的IL
直接使用FCL类型名称,更能够解决概念误差。
2.check与unchecked操作符
这两个操作符能够对单个表达式或域进行溢出的检查与否进行操作,若检查到溢出,则CLR会抛出OverflowException异常。
这个主要用于计算校验等。
3.引用类型与值类型
CLR支持两种类型:值类型与引用类型
引用类型总是从托管堆分配,C#中用new操作符返回对象内存地址,即指向对象数据的内存地址。
- 引用对象本身保存的是对象的内存地址
- 引用类型对象中其他字节(字段)总设为0
- 从托管堆分配对象时,可能强制执行一次垃圾回收
值类型的实例则一般在线程栈分配。
- 值类型对象本身包含了实例的字段,所以不包含指针
- 不受垃圾回收器控制
区分:任何称为类的类型都是引用类型,所有值类型都称为结构或枚举
private static class ReferenceVsValue {
// Reference type (because of 'class')
private class SomeRef { public Int32 x; }
// Value type (because of 'struct')
private struct SomeVal { public Int32 x; }
public static void Go() {
SomeRef r1 = new SomeRef(); // Allocated in heap
SomeVal v1 = new SomeVal(); // Allocated on stack
r1.x = 5; // Pointer dereference
v1.x = 5; // Changed on stack
Console.WriteLine(r1.x); // Displays "5"
Console.WriteLine(v1.x); // Also displays "5"
// The left side of Figure 5-2 reflects the situation
// after the lines above have executed.
SomeRef r2 = r1; // **Copies reference (pointer) only**
SomeVal v2 = v1; // Allocate on stack & copies members
r1.x = 8; // Changes r1.x and r2.x
v1.x = 9; // Changes v1.x, not v2.x
Console.WriteLine(r1.x); // Displays "8"
Console.WriteLine(r2.x); // Displays "8"
Console.WriteLine(v1.x); // Displays "9"
Console.WriteLine(v2.x); // Displays "5"
// The right side of Figure 5-2 reflects the situation
// after ALL the lines above have executed.
}
}