当前位置: 首页 > news >正文

C#数据类型

🧩 一、布尔值(bool

表示逻辑值:truefalse

bool isTrue = true;
bool isFalse = false;

📌 二、整数(Integer Types)

C# 支持多种有符号和无符号整数类型:

类型大小范围
sbyte8-bit-128 ~ 127
byte8-bit0 ~ 255
short16-bit-32,768 ~ 32,767
ushort16-bit0 ~ 65,535
int32-bit-2,147,483,648 ~ 2,147,483,647
uint32-bit0 ~ 4,294,967,295
long64-bit-9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807
ulong64-bit0 ~ 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)

类型大小精度后缀
float32-bit7 位数字F
double64-bit15~16 位数字D(默认)
decimal128-bit28~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);
}

🕰️ 十一、DateTimeTimeSpan

  • 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("输入无效");
}

🧠 总结对比表

数据类型/结构示例是否可变是否可空特点
booltrue, false布尔逻辑
int, long, double25, 3.14基础数值类型
string"Hello"不可变字符串
char'A'单个字符
enumColor.Red枚举常量
tuple(Name: "Tom", Age: 25)多值组合
arraynew int[] { 1, 2 }存储同类型集合
DateTimeDateTime.Now时间处理
int?null可空基本类型
objectobject 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

相关文章:

  • Python中常用的数据类型
  • 反向传播
  • 2、ubantu系统配置OpenSSH | 使用vscode或pycharm远程连接
  • 软件设计师考试《综合知识》CPU考点分析(2019-2023年)——求三连
  • 【QT 项目部署指南】使用 Inno Setup 打包 QT 程序为安装包(超详细图文教程)
  • 基于EFISH-SCB-RK3576/SAIL-RK3576的消防机器人控制器技术方案‌
  • Linux云计算训练营笔记day09(MySQL数据库)
  • 进度管理高分论文
  • 在 Hugo 博客中集成评论系统 Waline 与 浏览量统计
  • 基于“物理—事理—人理”的多源异构大数据融合探究
  • bfs搜索加标记连通区域id实现时间优化(空间换时间)
  • Go语言八股之Mysql事务
  • 扬州卓韵酒店用品:优质洗浴用品,提升酒店满意度与品牌形象
  • TCP(传输控制协议)建立连接的过程
  • Git/GitLab日常使用的命令指南来了!
  • 前端代码生成博客封面图片
  • 寻找两个正序数组的中位数 - 困难
  • 【BotSharp详细介绍——一步步实现MCP+LLM的聊天问答实例】
  • vscode c++编译onnxruntime cuda 出现的问题
  • 浏览器宝塔访问不了给的面板地址
  • A股三大股指低收:汽车股领涨,大金融走弱,两市成交近1.1万亿元
  • 侵害孩子者,必严惩不贷!3名性侵害未成年人罪犯今日执行死刑
  • 350种咖啡主题图书集结上海,20家参展书店买书送咖啡
  • 夜读丨母亲为燕子打开家门
  • 澳大利亚首例“漂绿”诉讼开庭:能源巨头因“碳中和”承诺遭起诉
  • 丹麦外交大臣拉斯穆森将访华