基本数据类型 #

一、数据类型概述 #

C#是一种强类型语言,每个变量都必须有明确的类型。C#的数据类型分为两大类:

类别 说明 存储位置
值类型 直接存储数据值
引用类型 存储数据的引用

二、值类型 #

2.1 整数类型 #

类型 范围 大小 后缀
sbyte -128 到 127 1字节 -
byte 0 到 255 1字节 -
short -32,768 到 32,767 2字节 -
ushort 0 到 65,535 2字节 -
int -2^31 到 2^31-1 4字节 -
uint 0 到 2^32-1 4字节 U/u
long -2^63 到 2^63-1 8字节 L/l
ulong 0 到 2^64-1 8字节 UL/ul

使用示例:

csharp
sbyte temperature = -10;
byte age = 25;
short year = 2024;
ushort port = 8080;
int count = 1000000;
uint population = 7_000_000_000;
long ticks = DateTime.Now.Ticks;
ulong fileSize = 1_000_000_000;

数字分隔符:

csharp
int million = 1_000_000;
long bigNumber = 1_000_000_000_000;

2.2 浮点类型 #

类型 范围 精度 大小 后缀
float ±1.5×10^-45 到 ±3.4×10^38 7位 4字节 F/f
double ±5.0×10^-324 到 ±1.7×10^308 15-16位 8字节 D/d
decimal ±1.0×10^-28 到 ±7.9×10^28 28-29位 16字节 M/m

使用示例:

csharp
float temperature = 36.5f;
double pi = 3.14159265359;
decimal price = 99.99m;
decimal balance = 1_000_000.50m;

精度比较:

csharp
float f = 0.1f + 0.2f;
double d = 0.1 + 0.2;
decimal m = 0.1m + 0.2m;

Console.WriteLine(f);
Console.WriteLine(d);
Console.WriteLine(m);

使用场景:

类型 适用场景
float 图形计算、科学计算
double 通用浮点计算
decimal 财务计算、货币

2.3 字符类型 #

csharp
char letter = 'A';
char digit = '7';
char symbol = '@';
char chinese = '中';

转义字符:

转义符 含义
\n 换行
\r 回车
\t 制表符
\\ 反斜杠
\' 单引号
\" 双引号
\0 空字符
\uXXXX Unicode字符
csharp
char newline = '\n';
char tab = '\t';
char unicode = '\u4E2D';

2.4 布尔类型 #

csharp
bool isValid = true;
bool isEmpty = false;
bool hasPermission = true;

布尔运算:

csharp
bool a = true;
bool b = false;

bool and = a && b;
bool or = a || b;
bool not = !a;

三、引用类型 #

3.1 字符串类型 #

csharp
string name = "张三";
string greeting = "Hello, World!";
string empty = string.Empty;
string nullStr = null;

字符串特性:

csharp
string s1 = "Hello";
string s2 = s1;
s2 = "World";

字符串拼接:

csharp
string firstName = "张";
string lastName = "三";

string fullName1 = firstName + lastName;
string fullName2 = string.Concat(firstName, lastName);
string fullName3 = $"{firstName}{lastName}";

3.2 对象类型 #

csharp
object obj1 = 42;
object obj2 = "Hello";
object obj3 = new List<int>();

int number = (int)obj1;
string text = (string)obj2;

3.3 动态类型 #

csharp
dynamic dyn = 42;
Console.WriteLine(dyn);

dyn = "Hello";
Console.WriteLine(dyn);

dyn = new List<int> { 1, 2, 3 };
Console.WriteLine(dyn.Count);

四、可空类型 #

4.1 可空值类型 #

csharp
int? nullableInt = null;
double? nullableDouble = 10.5;
bool? nullableBool = null;

if (nullableInt.HasValue)
{
    int value = nullableInt.Value;
}

int defaultValue = nullableInt ?? 0;

4.2 可空引用类型 #

csharp
string? nullableString = null;
string nonNullableString = "Hello";

nullableString?.ToString();

4.3 空值合并运算符 #

csharp
int? x = null;
int y = x ?? 0;

string? name = null;
string displayName = name ?? "未知用户";

五、类型系统架构 #

text
System.Object
├── 值类型 (ValueType)
│   ├── 简单类型
│   │   ├── 整数类型 (sbyte, byte, short, ushort, int, uint, long, ulong)
│   │   ├── 浮点类型 (float, double, decimal)
│   │   ├── 布尔类型 (bool)
│   │   └── 字符类型 (char)
│   ├── 枚举类型 (enum)
│   └── 结构类型 (struct)
│       ├── DateTime
│       ├── TimeSpan
│       ├── Guid
│       └── Tuple
└── 引用类型
    ├── 字符串 (string)
    ├── 数组 (array)
    ├── 类 (class)
    ├── 接口 (interface)
    ├── 委托 (delegate)
    └── 记录 (record)

六、内置类型别名 #

C#类型与.NET类型对照:

C#类型 .NET类型
int System.Int32
long System.Int64
short System.Int16
byte System.Byte
float System.Single
double System.Double
decimal System.Decimal
bool System.Boolean
char System.Char
string System.String
object System.Object
dynamic System.Object
csharp
int a = 10;
Int32 b = 10;

七、类型信息获取 #

7.1 typeof运算符 #

csharp
Type intType = typeof(int);
Type stringType = typeof(string);

Console.WriteLine(intType.Name);
Console.WriteLine(intType.FullName);
Console.WriteLine(intType.IsValueType);

7.2 GetType方法 #

csharp
int number = 42;
Type type = number.GetType();

Console.WriteLine(type.Name);

7.3 is运算符 #

csharp
object obj = "Hello";

if (obj is string)
{
    Console.WriteLine("是字符串");
}

if (obj is int)
{
    Console.WriteLine("是整数");
}

八、类型选择指南 #

8.1 整数类型选择 #

需求 推荐类型
通用整数 int
大整数 long
节省内存 byte, short
无符号 uint, ulong
文件大小 long
端口号 ushort

8.2 浮点类型选择 #

需求 推荐类型
通用浮点 double
货币计算 decimal
图形处理 float
科学计算 double

8.3 字符串vs StringBuilder #

csharp
string s = "";
for (int i = 0; i < 1000; i++)
{
    s += i;
}

var sb = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
    sb.Append(i);
}
string result = sb.ToString();

九、实战示例 #

9.1 学生成绩系统 #

csharp
public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public decimal Score { get; set; }
    public bool IsPassed => Score >= 60;
    public char Grade => Score switch
    {
        >= 90 => 'A',
        >= 80 => 'B',
        >= 70 => 'C',
        >= 60 => 'D',
        _ => 'F'
    };
}

9.2 商品价格计算 #

csharp
public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int Quantity { get; set; }
    
    public decimal TotalPrice => Price * Quantity;
    
    public decimal GetDiscountedPrice(decimal discountRate)
    {
        return TotalPrice * (1 - discountRate);
    }
}

var product = new Product
{
    Name = "笔记本电脑",
    Price = 5999.99m,
    Quantity = 2
};

Console.WriteLine($"商品:{product.Name}");
Console.WriteLine($"单价:{product.Price:C}");
Console.WriteLine($"数量:{product.Quantity}");
Console.WriteLine($"总价:{product.TotalPrice:C}");

十、总结 #

基本数据类型要点:

类型 说明
int 32位整数
long 64位整数
double 双精度浮点
decimal 高精度十进制
bool 布尔值
char 单个字符
string 字符串

下一步,让我们学习类型转换!

最后更新:2026-03-26