C#数据类型
🧩 一、布尔值(bool
)
表示逻辑值:true
或 false
bool isTrue = true;
bool isFalse = false;
📌 二、整数(Integer Types)
C# 支持多种有符号和无符号整数类型:
类型 | 大小 | 范围 |
---|---|---|
sbyte | 8-bit | -128 ~ 127 |
byte | 8-bit | 0 ~ 255 |
short | 16-bit | -32,768 ~ 32,767 |
ushort | 16-bit | 0 ~ 65,535 |
int | 32-bit | -2,147,483,648 ~ 2,147,483,647 |
uint | 32-bit | 0 ~ 4,294,967,295 |
long | 64-bit | -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807 |
ulong | 64-bit | 0 ~ 18,446,744,073,709,551,615 |
示例:
int age = 25;
long population = 7_800_000_000L; // 使用 L 表示 long
🔤 三、整数符号(Signed vs Unsigned)
- 有符号:
sbyte
,short
,int
,long
- 无符号:
byte
,ushort
,uint
,ulong
🧱 四、使用下划线 _
提高可读性(C# 7.0+)
int million = 1_000_000;
long bigNumber = 0x1234_5678_9ABC_DEF0;
⚠️ 五、算术溢出(Arithmetic Overflow)
默认情况下,C# 不会检查整数运算是否溢出。可以通过 checked
强制检查:
int a = int.MaxValue;
try
{checked{int b = a + 1; // 抛出 OverflowException}
}
catch (OverflowException)
{Console.WriteLine("发生溢出!");
}
🧮 六、浮点数(Floating Point Types)
类型 | 大小 | 精度 | 后缀 |
---|---|---|---|
float | 32-bit | 7 位数字 | F |
double | 64-bit | 15~16 位数字 | D (默认) |
decimal | 128-bit | 28~29 位精确数字 | M |
示例:
float f = 3.14F;
double d = 3.1415926535;
decimal m = 3.1415926535M;
🎖️ 七、枚举(enum
)
表示一组命名的整数常量。
enum Color
{Red,Green,Blue
}Color selected = Color.Green;
Console.WriteLine(selected); // 输出:Green
🧩 八、元组(Tuples)
用于返回多个值或临时组合多个变量。
var person = (Name: "Tom", Age: 25);
Console.WriteLine($"{person.Name} 是 {person.Age} 岁");
✒️ 九、字符串与字符
char
:单个 Unicode 字符,用' '
包裹。string
:字符序列,用" "
包裹。
char letter = 'A';
string greeting = "Hello, World!";
📦 十、数组(Array)
存储相同类型的多个元素。
int[] numbers = { 1, 2, 3 };
string[] names = new string[] { "Alice", "Bob" };foreach (int n in numbers)
{Console.WriteLine(n);
}
🕰️ 十一、DateTime
和 TimeSpan
DateTime
:表示日期和时间。TimeSpan
:表示时间间隔。
DateTime now = DateTime.Now;
Console.WriteLine("当前时间:" + now);TimeSpan duration = TimeSpan.FromHours(2);
Console.WriteLine("两小时后是:" + now.Add(duration));
🔁 十二、类型转换(Type Conversion)
隐式转换(自动):
int i = 100;
long l = i; // 隐式转换
显式转换(强制):
double d = 9.99;
int j = (int)d; // 显式转换,结果为 9
❓ 十三、可空类型(Nullable Types)
允许基本类型为 null
:
int? nullableInt = null;
bool? isReady = true;if (nullableInt.HasValue)
{Console.WriteLine(nullableInt.Value);
}
else
{Console.WriteLine("值为空");
}
简写方式(??
运算符):
int result = nullableInt ?? 0; // 如果为 null,取 0
🔄 十四、转换与解析方法
方法 | 示例 | 说明 |
---|---|---|
ToString() | 123.ToString() → "123" | 转为字符串 |
Parse() | int.Parse("123") | 字符串转为数值 |
TryParse() | int.TryParse("abc", out int x) | 安全转换,失败不抛异常 |
Convert.ToInt32() | Convert.ToInt32("123") | 更通用的转换方法 |
示例:
string input = "123";
if (int.TryParse(input, out int value))
{Console.WriteLine("转换成功:" + value);
}
else
{Console.WriteLine("输入无效");
}
🧠 总结对比表
数据类型/结构 | 示例 | 是否可变 | 是否可空 | 特点 |
---|---|---|---|---|
bool | true , false | ✅ | ❌ | 布尔逻辑 |
int , long , double | 25 , 3.14 | ✅ | ❌ | 基础数值类型 |
string | "Hello" | ❌ | ✅ | 不可变字符串 |
char | 'A' | ✅ | ❌ | 单个字符 |
enum | Color.Red | ✅ | ❌ | 枚举常量 |
tuple | (Name: "Tom", Age: 25) | ✅ | ✅ | 多值组合 |
array | new int[] { 1, 2 } | ✅ | ✅ | 存储同类型集合 |
DateTime | DateTime.Now | ✅ | ❌ | 时间处理 |
int? | null | ✅ | ✅ | 可空基本类型 |
object | object obj = 123; | ✅ | ✅ | 通用引用类型 |
🧩 项目名称:学生信息管理系统(控制台版)
功能说明:
这是一个简单的控制台程序,用于录入和展示学生的部分基本信息,并演示 C# 的多种语言特性。
✅ 完整代码模板(Program.cs)
using System;class Program
{// 枚举:表示学生性别enum Gender{Male,Female,Other}// 结构体:表示学生信息struct Student{public string Name;public int Age;public Gender Gender;public DateTime BirthDate;public decimal Score;public bool? IsPassed; // 可空布尔值}static void Main(){Console.WriteLine("欢迎使用学生信息管理系统");// 录入姓名Console.Write("请输入学生姓名:");string name = Console.ReadLine();// 录入年龄并验证Console.Write("请输入学生年龄:");string ageInput = Console.ReadLine();int age = int.Parse(ageInput);// 录入性别Console.WriteLine("请选择性别(0=男,1=女,2=其他):");int genderValue = int.Parse(Console.ReadLine());Gender gender = (Gender)genderValue;// 录入出生日期Console.Write("请输入出生日期(yyyy-MM-dd):");string dateStr = Console.ReadLine();DateTime birthDate = DateTime.Parse(dateStr);// 录入成绩Console.Write("请输入学生成绩(0.00 - 100.00):");string scoreStr = Console.ReadLine();decimal score = decimal.Parse(scoreStr);// 判断是否通过(模拟逻辑)bool? isPassed = null;if (score >= 60)isPassed = true;else if (score < 60 && score >= 0)isPassed = false;// 创建学生结构体实例Student student = new Student{Name = name,Age = age,Gender = gender,BirthDate = birthDate,Score = score,IsPassed = isPassed};// 输出学生信息Console.WriteLine("\n=== 学生信息 ===");Console.WriteLine($"姓名:{student.Name}");Console.WriteLine($"年龄:{student.Age}");Console.WriteLine($"性别:{student.Gender}");Console.WriteLine($"出生日期:{student.BirthDate:yyyy年MM月dd日}");Console.WriteLine($"成绩:{student.Score:F2}");Console.WriteLine($"是否通过:{(student.IsPassed.HasValue ? student.IsPassed.Value ? "是" : "否" : "未判定")}");// 使用元组返回多个值(示例)var result = CalculateStatistics(85.5M, 90.0M, 78.0M);Console.WriteLine($"\n平均分:{result.average:F2},最高分:{result.max:F2}");// 等待用户按键退出Console.WriteLine("\n按任意键退出...");Console.ReadKey();}// 方法:计算统计信息(使用元组返回多个值)static (decimal average, decimal max) CalculateStatistics(params decimal[] scores){decimal sum = 0;decimal max = decimal.MinValue;foreach (var score in scores){sum += score;if (score > max)max = score;}return (sum / scores.Length, max);}
}
📋 示例运行输出:
欢迎使用学生信息管理系统
请输入学生姓名:张三
请输入学生年龄:20
请选择性别(0=男,1=女,2=其他):
0
请输入出生日期(yyyy-MM-dd):2004-03-15
请输入学生成绩(0.00 - 100.00):88.5=== 学生信息 ===
姓名:张三
年龄:20
性别:Male
出生日期:2004年03月15日
成绩:88.50
是否通过:是平均分:85.50,最高分:90.00按任意键退出...
🧠 涵盖的知识点总结:
技术点 | 是否使用 |
---|---|
布尔值 | ✅ |
整数、浮点数 | ✅ |
枚举 | ✅ |
元组 | ✅ |
字符串插值 | ✅ |
字符 | ❌(可自行扩展) |
数组 | ✅(params decimal[] ) |
DateTime | ✅ |
类型转换 | ✅(Parse , ToString ) |
可空类型 | ✅(bool? ) |
转换与解析方法 | ✅(int.Parse , decimal.Parse , DateTime.Parse ) |