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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值