C# 数据类型

值类型与引用类型、内置类型、默认值、以及 `var` 与 `dynamic`。

Beginner
Key Points值类型存在栈上(或内联在对象里),引用类型指向堆上的对象。

两大类

CategoryTypesAssignment
值类型int double bool char struct enum复制整个值
引用类型string class array delegate object复制引用
C#
// 值类型:复制
int a = 10;
int b = a;
b = 20;
Console.WriteLine($"a={a} b={b}");

// 引用类型:共享
int[] x = { 1, 2 };
int[] y = x;
y[0] = 99;
Console.WriteLine($"x[0]={x[0]}");
Output
a=10 b=20
x[0]=99

内置类型

TypeSizeRangeAlias
Int324 字节±21 亿int
Int648 字节±9.2e18long
Int162 字节±32767short
Byte1 字节0~255byte
Single4 字节约 7 位有效数字float
Double8 字节约 15 位double
Decimal16 字节28 位,精确十进制decimal
Boolean1 字节true/falsebool
Char2 字节UTF-16 单元char
String引用类型不可变string

金额用 decimal

C#
double d = 0.1 + 0.2;
Console.WriteLine(d);

decimal m = 0.1m + 0.2m;
Console.WriteLine(m);
Output
0.30000000000000004
0.3
**Money, tax rates and prices must use decimal.** double is binary floating point, so 0.1 is inexact and errors accumulate into real money problems. decimal literals need the m suffix.

默认值

C#
Console.WriteLine(default(int));
Console.WriteLine(default(bool));
Console.WriteLine(default(double));
Console.WriteLine(default(char) == '\0');
Console.WriteLine(default(string) == null);

// 值类型不能直接赋 null,要加 ?
int? n = null;
Console.WriteLine(n.HasValue);
Output
0
False
0
True
True
False

var 与 dynamic

C#
var a = 10;                 // 编译期推断为 int,之后不能改成 string
var list = new List<int>();
var dict = new Dictionary<string, int>();

dynamic b = 10;             // 运行期决定类型
b = "现在变字符串了";
Console.WriteLine(b);

Console.WriteLine(a.GetType().Name);
Output
现在变字符串了
Int32

var is pure syntax sugar; the type is fixed at compile time with no performance or safety cost. dynamic defers checking to runtime — slower and prone to runtime failures.

Friends & Partners