C# 中的数据类型可以分为两大类:值类型(Value Types)和引用类型(Reference Types)。以下是完整的分类列表:
一、值类型(Value Types)
1. 简单类型(内置值类型)
整数类型
| 类型 |
大小 |
范围 |
别名 |
sbyte |
8-bit |
-128 到 127 |
System.SByte |
byte |
8-bit |
0 到 255 |
System.Byte |
short |
16-bit |
-32,768 到 32,767 |
System.Int16 |
ushort |
16-bit |
0 到 65,535 |
System.UInt16 |
int |
32-bit |
-2,147,483,648 到 2,147,483,647 |
System.Int32 |
uint |
32-bit |
0 到 4,294,967,295 |
System.UInt32 |
long |
64-bit |
-9,223,372,036,854,775,808 到 9,223,372,036,854,775,807 |
System.Int64 |
ulong |
64-bit |
0 到 18,446,744,073,709,551,615 |
System.UInt64 |
浮点类型
| 类型 |
大小 |
精度 |
别名 |
float |
32-bit |
~6-9 位小数 |
System.Single |
double |
64-bit |
~15-17 位小数 |
System.Double |
decimal |
128-bit |
28-29 位小数 |
System.Decimal |
其他简单类型
| 类型 |
描述 |
别名 |
bool |
布尔值 (true/false) |
System.Boolean |
char |
Unicode 字符 (16-bit) |
System.Char |
2. 枚举类型(Enum)
enum Weekday { Monday, Tuesday } // 继承自System.Enum
3. 结构体类型(Struct)
struct Point { public int X; public int Y; } // 自定义值类型
4. 可空值类型(Nullable)
int? nullableInt = null; // System.Nullable<T>
二、引用类型(Reference Types)
1. 类类型(Class)
| 类型 |
描述 |
object |
所有类型的基类 |
string |
不可变字符串 |
| 自定义类 |
class MyClass { } |
| 动态类型 |
dynamic (运行时绑定) |
2. 接口类型(Interface)
interface IDrawable { void Draw(); }
3. 数组类型(Array)
int[] numbers = new int[10]; // 一维数组
string[,] grid = new string[5,5]; // 多维数组
4. 委托类型(Delegate)
delegate void MyDelegate(string msg); // 自定义委托
Action<int> action; // 内置泛型委托
Func<int, bool> func; // 内置泛型委托
5. 记录类型(Record)(C# 9+)
record Person(string Name, int Age); // 不可变引用类型
三、特殊类型
| 类型 |
描述 |
void |
表示无返回值 |
nint/nuint
|
平台相关整数 (C# 9+) |
var |
隐式类型推断 (编译时确定类型) |
四、类型关系图
System.Object
├── 值类型 (System.ValueType)
│ ├── 简单类型 (int, float, bool等)
│ ├── 枚举 (enum)
│ └── 结构体 (struct)
└── 引用类型
├── 类 (class)
├── 接口 (interface)
├── 数组
├── 委托
└── 字符串 (string)
五、关键区别:值类型 vs 引用类型
| 特性 |
值类型 |
引用类型 |
| 内存分配位置 |
栈(stack) |
堆(heap) |
| 默认值 |
各类型的默认值 (如0/false) |
null |
| 赋值行为 |
复制整个值 |
复制引用(指向同一对象) |
| 继承 |
只能实现接口 |
可继承类和实现接口 |
| 典型示例 |
int, struct, enum |
class, string, array |
掌握这些数据类型是C#开发的基础,理解它们的特性和适用场景对编写高效代码至关重要。