类型系统
翻译整理自 C# 类型系统 与 Built-in types。
1. 内置类型
| 类型 | .NET 类型 | 大小 | 范围 |
|---|---|---|---|
bool |
Boolean | 1 | true/false |
byte |
Byte | 1 | 0~255 |
sbyte |
SByte | 1 | -128~127 |
char |
Char | 2 | UTF-16 |
short |
Int16 | 2 | -32768~32767 |
ushort |
UInt16 | 2 | 0~65535 |
int |
Int32 | 4 | -2³¹~2³¹-1 |
uint |
UInt32 | 4 | 0~2³²-1 |
long |
Int64 | 8 | -2⁶³~2⁶³-1 |
ulong |
UInt64 | 8 | 0~2⁶⁴-1 |
float |
Single | 4 | ±3.4×10³⁸ |
double |
Double | 8 | ±1.7×10³⁰⁸ |
decimal |
Decimal | 16 | 高精度十进制 |
string |
String | — | 字符串 |
object |
Object | — | 所有类型基类 |
2. 值类型 vs 引用类型
- 值类型:分配在栈上,赋值拷贝。如
int、struct、enum、bool - 引用类型:分配在堆上,赋值共享引用。如
class、string、object、array
int a = 1;
int b = a; // 拷贝
b = 2;
Console.WriteLine(a); // 1
var s1 = new StringBuilder("x");
var s2 = s1; // 引用同一对象
s2.Append("y");
Console.WriteLine(s1); // "xy"特殊:
string虽是引用类型但表现为值语义(不可变)。
3. 装箱与拆箱
值类型↔对象互转:
int x = 5;
object o = x; // 装箱
int y = (int)o; // 拆箱频繁装箱有性能损耗,可用泛型集合避免。
4. struct 自定义值类型
public struct Point
{
public int X, Y;
public Point(int x, int y) { X = x; Y = y; }
public double Distance => Math.Sqrt(X * X + Y * Y);
}
Point p = new Point(3, 4);struct 不支持继承(可 sealed),默认无参构造(C# 10 起可显式定义)。
5. enum 枚举
public enum Color { Red, Green, Blue }
public enum Http : int { OK = 200, NotFound = 404 }
Color c = Color.Red;
int v = (int)c;
Color r = (Color)1;Flags:
[Flags]
public enum Perms { Read = 1, Write = 2, Execute = 4 }
var p = Perms.Read | Perms.Write;
Console.WriteLine(p); // Read, Write6. 可空类型 nullable
int? n = null;
if (n.HasValue) Console.WriteLine(n.Value);
int x = n ?? 0; // null 合并
n ??= 5; // ??= 赋值(C# 8+)7. 可空引用类型(C# 8+)
#nullable enable
string s1 = null; // ❌ 警告
string? s2 = null; // OK启用后编译器对引用类型做 null 检查。
8. record 类型(C# 9+)
值语义的引用类型,自动生成相等比较、ToString:
public record Person(string Name, int Age);
var p = new Person("Alice", 30);
var q = p with { Age = 31 }; // 非破坏性修改
Console.WriteLine(p == q); // False(值比较)C# 10+ record struct:
public readonly record struct Point(int X, int Y);9. var 与类型推断
var x = 1; // int
var s = "hello"; // string
var list = new List<int>(); // List<int>10. 类型转换
隐式
int i = 5;
double d = i; // 安全提升显式
double pi = 3.14;
int n = (int)pi; // 3
object o = "x";
string s = (string)o; // 强转as 与 is
object o = "x";
string s = o as string; // 失败返回 null
if (o is string str) {
Console.WriteLine(str);
}C# 7+ 模式匹配:
if (o is int n) Console.WriteLine(n);
if (o is string { Length: > 3 } s) Console.WriteLine(s);11. 元组
var t = (1, "x", 3.14);
Console.WriteLine(t.Item1);
(string name, int age) person = ("Alice", 30);
Console.WriteLine(person.name);
// 解构
var (name, age) = GetPerson();小结
C# 类型系统结合了值/引用类型、可空、record、元组,在强类型与表达力之间取得很好平衡。