C# 数据类型(C# Data Types)详解
                           
天天向上
发布: 2025-04-06 23:27:48

原创
11 人浏览过

本文章深入讲解 C# 数据类型(C# Data Types)全面、系统地介绍 C# 支持的各种数据类型,通过本章节你将了解到:

  • C# 中的数据类型分类
  • 每种类型的用途和特性
  • 内存大小、默认值、范围
  • 类型转换
  • 官方文档链接

📌 目录导航

  1. C# 数据类型总览
  2. 值类型(Value Types)
  3. 引用类型(Reference Types)
  4. 指针类型(Pointer Types)
  5. 类型转换(Type Conversion)
  6. var 与 dynamic 关键字
  7. Nullable 类型(可空值类型)
  8. 类型检查与转换操作符
  9. 官方权威文档链接

1️⃣ 数据类型总览

C# 数据类型主要分为三类:

分类示例
值类型int, float, bool, char
引用类型string, object, 自定义类
指针类型(不常用)int*, char*(需 unsafe)

参考官方文档:
👉 Built-in Types – Microsoft Docs


2️⃣ 值类型(Value Types)

值类型直接包含数据,分配在 栈上,变量拥有自己的副本。

🔹 常见值类型

类型占用空间默认值取值范围(部分)
int4 字节0-2,147,483,648 到 2,147,483,647
long8 字节0L±9×10¹⁸
float4 字节0.0f±1.5×10⁻⁴⁵ 到 ±3.4×10³⁸
double8 字节0.0d±5.0×10⁻³²⁴ 到 ±1.7×10³⁰⁸
decimal16 字节0.0m±1.0×10⁻²⁸ 到 ±7.9×10²⁸
bool1 字节falsetruefalse
char2 字节'\0'Unicode 字符,如 'A''中'
byte1 字节00 到 255
int age = 30;
float price = 19.99f;
bool isAdmin = false;
char grade = 'A';

3️⃣ 引用类型(Reference Types)

引用类型存储 引用地址,实际数据存在于 上。

🔹 常见引用类型

类型说明
string字符串(不可变)
object所有类型的基类
自定义类class, interface
array数组,如 int[], string[]
string name = "Alice";
object obj = 123;
int[] scores = {90, 80, 70};

4️⃣ 指针类型(Pointer Types)

只有在 unsafe 上下文中 才能使用,主要用于系统编程或性能关键代码。

unsafe
{
    int x = 10;
    int* px = &x;
    Console.WriteLine(*px);  // 输出:10
}

⚠️ 使用 unsafe 需要开启编译器设置,并不推荐一般业务逻辑中使用。


5️⃣ 类型转换(Type Conversion)

🔸 隐式转换(小转大)

int a = 100;
long b = a; // 自动转换

🔸 显式转换(大转小,需强制)

double x = 12.34;
int y = (int)x; // 手动转换,y = 12

🔸 Convert

string str = "123";
int num = Convert.ToInt32(str);

6️⃣ var 与 dynamic

🔹 var:编译时类型推断(静态)

var age = 20;       // int
var name = "Tom";   // string

📌 一旦类型被推断,不能再改变。

🔹 dynamic:运行时绑定(动态)

dynamic x = 10;
x = "hello"; // 可变类型,但存在运行时错误风险

7️⃣ Nullable 类型(可空值)

值类型不能为 null,除非使用 ? 修饰:

int? age = null;

if (age.HasValue)
{
    Console.WriteLine(age.Value);
}

8️⃣ 类型检查与转换操作符

操作符示例含义
isobj is string类型判断
asobj as string类型转换,失败返回 null
typeoftypeof(int)获取类型信息
.GetType()x.GetType()运行时获取实例类型

9️⃣ 官方权威文档链接

  • 🧾 C# 类型系统概述:
    https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/types
  • 📦 所有内置类型(含大小、范围):
    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/built-in-types
  • 🔄 类型转换:
    https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/type-conversions

总结

类型分类示例特点
值类型int, bool, char栈上分配,高性能
引用类型string, object, 类堆上分配,灵活但需注意内存管理
指针类型int*, char*高级用法,需 unsafe
Nullableint?值类型也可为 null
动态类型dynamic运行时灵活,低性能、易错

是否需要我接下来帮你整理「C# 流程控制语句」或「C# 类与对象」的详细学习资料?我可以继续为你做系列讲解。

发表回复 0

Your email address will not be published. Required fields are marked *