在 C# 中,数据类型用于定义变量能够存储什么样的数据。C# 是一种强类型语言,所有变量在使用前都必须声明类型。
一、值类型(Value Type)
值类型直接存储数据本身,通常存储在栈(Stack)中。
1. 整数类型
| 类型 | 大小 | 范围 |
|---|---|---|
byte |
1字节 | 0 ~ 255 |
sbyte |
1字节 | -128 ~ 127 |
short |
2字节 | -32,768 ~ 32,767 |
ushort |
2字节 | 0 ~ 65,535 |
int |
4字节 | -2³¹ ~ 2³¹-1 |
uint |
4字节 | 0 ~ 2³²-1 |
long |
8字节 | -2⁶³ ~ 2⁶³-1 |
ulong |
8字节 | 0 ~ 2⁶⁴-1 |
cs
int age = 25;
long population = 1400000000L;
2. 浮点类型
| 类型 | 大小 | 精度 |
|---|---|---|
float |
4字节 | 约7位有效数字 |
double |
8字节 | 约15~16位有效数字 |
decimal |
16字节 | 28~29位有效数字 |
cs
float f = 3.14f;
double d = 3.1415926;
decimal money = 999.99m;
财务计算推荐使用
decimal。
3. 字符类型
cs
char gender = '男';
char letter = 'A';
特点:
- 使用单引号
' ' - 只能存储一个字符
- 占2字节(Unicode)
4. 布尔类型
cs
bool isLogin = true;
bool isAdmin = false;
取值只有:
cs
true
false
5. 日期时间类型
cs
DateTime now = DateTime.Now;
Console.WriteLine(now);
输出:
2026/6/22 10:30:00
二、引用类型(Reference Type)
引用类型存储对象的地址,数据通常存储在堆(Heap)中。
1. string 字符串
cs
string name = "张三";
Console.WriteLine(name);
常用操作:
cs
string str = "Hello";
Console.WriteLine(str.Length);
Console.WriteLine(str.ToUpper());
Console.WriteLine(str.ToLower());
2. object 类型
所有类型的基类。
cs
object obj1 = 100;
object obj2 = "Hello";
object obj3 = true;
3. 数组
cs
int[] nums = { 10, 20, 30, 40 };
Console.WriteLine(nums[0]);
输出:
cs
10
4. 类(Class)
cs
class Student
{
public string Name;
public int Age;
}
Student stu = new Student();
stu.Name = "张三";
stu.Age = 20;
三、特殊类型
var(隐式类型)
编译器自动推断类型。
cs
var name = "张三";
var age = 18;
var salary = 8000.5;
实际类型:
cs
string
int
double
注意:
cs
var a = null; // 错误
dynamic(动态类型)
运行时确定类型。
cs
dynamic data = "Hello";
Console.WriteLine(data.Length);
data = 100;
Console.WriteLine(data);
特点:
- 编译时不检查类型
- 运行时检查
- 使用灵活但效率较低
nullable(可空类型)
允许值类型存储 null。
cs
int? age = null;
age = 20;
等价于:
Nullable<int> age = null;
四、类型转换
1. 隐式转换
小类型转大类型
int num = 100;
long l = num;
2. 显式转换
大类型转小类型
cs
double d = 3.14;
int num = (int)d;
Console.WriteLine(num);
输出:
3
3. Convert转换
string str = "123";
int num = Convert.ToInt32(str);
Console.WriteLine(num);
4. Parse转换
string str = "100";
int num = int.Parse(str);
5. TryParse(推荐)
避免程序异常。
cs
string str = "abc";
bool result = int.TryParse(str, out int num);
Console.WriteLine(result);
输出:
False
五、常用数据类型总结
cs
int age = 18;
double score = 95.5;
decimal money = 1000.50m;
char sex = '男';
bool isPass = true;
string name = "张三";
DateTime now = DateTime.Now;
面试常问
1. string 是值类型还是引用类型?
答:string 是引用类型,但具有值类型的部分特性(不可变对象)。
2. float、double、decimal 的区别?
float:7位精度double:15~16位精度(默认)decimal:28~29位精度(财务计算)
3. var 和 dynamic 的区别?
| var | dynamic |
|---|---|
| 编译时确定类型 | 运行时确定类型 |
| 类型安全 | 不安全 |
| 性能较高 | 性能较低 |