单元1 · C# 环境与基础语法
.NET 环境、Main 入口、Console 输出、变量与常量
- 入口:Main 方法是程序入口;Console 类负责控制台交互。
- 类型:C# 强类型;int/double/string/bool 常用;var 推断。
- 输出:$ 字符串插值、{0} 复合格式化、F2/N2 数值格式。
实训1.1 Hello World 与 Main 入口
编写第一个 C# 程序,输出问候语,说明 Main 方法的作用。
C# 程序从 Main 方法开始;Console.WriteLine 输出并换行。
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, C#!");
Console.WriteLine("当前时间:" + DateTime.Now);
}
}
实训1.2 变量与常量
声明 int、double、string、bool 变量和一个 const 常量并输出。
C# 是强类型语言;var 可推断类型;const 定义编译期常量。
using System;
class Program
{
static void Main()
{
int age = 21;
double pi = 3.14159;
string name = "C#";
bool isCool = true;
const int MAX_COUNT = 100;
Console.WriteLine($"语言:{name},版本使用 {age}");
Console.WriteLine($"圆周率:{pi:F2}");
Console.WriteLine($"是否流行:{isCool}");
Console.WriteLine($"最大数量:{MAX_COUNT}");
}
}
实训1.3 字符串插值与格式化
用字符串插值 $、复合格式化 {0}、以及 ToString 格式化输出数值。
$ 前缀插值最常用;{0:N2} 千分位;F2 保留两位小数。
using System;
class Program
{
static void Main()
{
string name = "Alice";
int score = 92;
double price = 1234.5678;
Console.WriteLine($"姓名:{name},成绩:{score} 分");
Console.WriteLine("复合格式化:{0} 得了 {1} 分", name, score);
Console.WriteLine($"价格:{price:F2} 元");
Console.WriteLine($"价格:{price:N2} 元");
}
}
实训1.4 输入与类型转换
用 Console.ReadLine 读取用户输入并转换为数字,计算平方输出。
ReadLine 返回字符串;int.Parse 或 TryParse 转换;TryParse 更安全。
using System;
class Program
{
static void Main()
{
Console.Write("请输入一个整数:");
string input = Console.ReadLine();
if (int.TryParse(input, out int n))
{
Console.WriteLine($"{n} 的平方是 {n * n}");
}
else
{
Console.WriteLine("输入无效");
}
}
}
单元2 · 数据类型与运算符
值类型/引用类型、算术/比较/逻辑运算符、类型转换
- 运算:int/int 整除;% 取余;Math.PI/Math.Sqrt 数学函数。
- 比较:== != && || ! 与 Java 一致。
- 转换:int.Parse/TryParse/Convert/(double) 强转。
实训2.1 基础运算
给定整数 17 和 5,输出和、差、积、商(整除)、余数。
C# 中两个 int 相除得 int(整除);% 取余。
using System;
class Program
{
static void Main()
{
int a = 17, b = 5;
Console.WriteLine($"和:{a + b}");
Console.WriteLine($"差:{a - b}");
Console.WriteLine($"积:{a * b}");
Console.WriteLine($"整除商:{a / b}");
Console.WriteLine($"余数:{a % b}");
}
}
实训2.2 浮点运算与转换
计算半径为 7.5 的圆的周长与面积(π=3.14159)。
double 参与浮点运算;Math.PI 更精确;F4 保留四位。
using System;
class Program
{
static void Main()
{
double r = 7.5;
double circumference = 2 * Math.PI * r;
double area = Math.PI * r * r;
Console.WriteLine($"周长:{circumference:F4}");
Console.WriteLine($"面积:{area:F4}");
}
}
实训2.3 比较与逻辑运算
a=8、b=12,输出 a>b、a!=b、a<10 && b>10、!(a==8)。
== 相等、!= 不等;&& 与、|| 或、! 非。
using System;
class Program
{
static void Main()
{
int a = 8, b = 12;
Console.WriteLine($"a > b:{a > b}");
Console.WriteLine($"a != b:{a != b}");
Console.WriteLine($"a<10 && b>10:{a < 10 && b > 10}");
Console.WriteLine($"!(a == 8):{!(a == 8)}");
}
}
实训2.4 类型转换综合
把字符串 "42" 转 int 加 8,再转 double 与 string,输出各类型。
int.Parse/Convert/ToString 显式转换;(double) 强制转换。
using System;
class Program
{
static void Main()
{
string s = "42";
int n = int.Parse(s) + 8;
double d = n;
string text = d.ToString();
Console.WriteLine($"整数:{n},类型:{n.GetType().Name}");
Console.WriteLine($"浮点:{d},类型:{d.GetType().Name}");
Console.WriteLine($"字符串:{text},类型:{text.GetType().Name}");
}
}
单元3 · 流程控制:分支结构
if/else if/else、switch 表达式
- if/else:逐级判断;单语句可省略花括号。
- switch:case + break;C# 8 switch 表达式更简洁。
- 模式:is 类型模式匹配;三元 ?:。
实训3.1 if 判断成绩等级
成绩 score=85,输出等级:>=90 优秀、>=80 良好、>=60 及格、否则不及格。
if / else if / else 逐级判断。
using System;
class Program
{
static void Main()
{
int score = 85;
if (score >= 90)
Console.WriteLine("优秀");
else if (score >= 80)
Console.WriteLine("良好");
else if (score >= 60)
Console.WriteLine("及格");
else
Console.WriteLine("不及格");
}
}
实训3.2 switch 判断星期
用 switch 把数字 1-7 映射为星期,输入 4 输出对应星期。
switch 匹配 case;每支 break;default 兜底。
using System;
class Program
{
static void Main()
{
int day = 4;
switch (day)
{
case 1: Console.WriteLine("星期一"); break;
case 2: Console.WriteLine("星期二"); break;
case 3: Console.WriteLine("星期三"); break;
case 4: Console.WriteLine("星期四"); break;
case 5: Console.WriteLine("星期五"); break;
case 6: Console.WriteLine("星期六"); break;
case 7: Console.WriteLine("星期日"); break;
default: Console.WriteLine("无效输入"); break;
}
}
}
实训3.3 switch 表达式
用 switch 表达式把颜色名称映射为十六进制代码。
switch 表达式是 C# 8 特性,=> 分支、_ 兜底,返回表达式结果。
using System;
class Program
{
static void Main()
{
string color = "red";
string hex = color switch
{
"red" => "#FF0000",
"green" => "#00FF00",
"blue" => "#0000FF",
_ => "#000000"
};
Console.WriteLine($"{color} 的十六进制:{hex}");
}
}
实训3.4 三元与模式匹配
判断 n=15 奇偶并用 is 模式匹配判断字符串类型。
三元 ?: ;is 运算符做类型与模式检查。
using System;
class Program
{
static void Main()
{
int n = 15;
Console.WriteLine(n % 2 == 0 ? "偶数" : "奇数");
object value = "hello";
if (value is string text)
{
Console.WriteLine($"是字符串,长度:{text.Length}");
}
}
}
单元4 · 循环结构
for、while、foreach、break/continue
- for:标准三要素循环。
- foreach:遍历集合无需索引,最常用。
- 控制:break/continue 控制循环流向。
实训4.1 for 求和 1 到 100
用 for 循环计算 1+2+...+100 的和并输出。
标准 for 三要素;累加器初始 0。
using System;
class Program
{
static void Main()
{
int sum = 0;
for (int i = 1; i <= 100; i++)
sum += i;
Console.WriteLine($"1 到 100 的和:{sum}");
}
}
实训4.2 打印乘法表
输出 9x9 乘法表,每行一个乘数。
嵌套两层 for;内层次数随外层变化。
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 9; i++)
{
string row = "";
for (int j = 1; j <= i; j++)
row += $"{j}x{i}={i * j} ";
Console.WriteLine(row);
}
}
}
实训4.3 foreach 遍历数组
遍历成绩数组 {55, 90, 72, 88, 45},输出及格者。
foreach 无需索引即可遍历;continue 跳过。
using System;
class Program
{
static void Main()
{
int[] scores = { 55, 90, 72, 88, 45 };
foreach (int score in scores)
{
if (score < 60) continue;
Console.WriteLine($"{score} 分:及格");
}
}
}
实训4.4 break 与 continue 综合
输出 1 到 20 中能被 3 整除的数,遇到 15 用 break 结束。
break 终止循环;continue 跳过当前迭代。
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 20; i++)
{
if (i == 15) break;
if (i % 3 != 0) continue;
Console.WriteLine(i);
}
}
}
单元5 · 函数与方法
方法定义、参数默认值、ref/out、重载、递归
- 方法:static 方法声明在类内;return 返回值。
- 参数:默认参数、命名参数、ref/out 引用传递。
- 进阶:递归要有终止条件;重载按签名区分。
实训5.1 定义求和方法
定义 Add(int a, int b) 返回两数之和并调用输出。
static 方法 + 返回类型 + 参数类型;C# 方法需声明在类中。
using System;
class Program
{
static int Add(int a, int b)
{
return a + b;
}
static void Main()
{
Console.WriteLine($"Add(10, 20) = {Add(10, 20)}");
Console.WriteLine($"Add(3, 7) = {Add(3, 7)}");
}
}
实训5.2 默认参数与命名参数
定义 Greet(string name, string greeting = "你好"),测试默认与自定义。
默认参数在未传时生效;调用可命名参数传值。
using System;
class Program
{
static string Greet(string name, string greeting = "你好")
{
return $"{greeting},{name}!";
}
static void Main()
{
Console.WriteLine(Greet("小明"));
Console.WriteLine(Greet("小红", "早上好"));
Console.WriteLine(Greet(greeting: "欢迎", name: "小刚"));
}
}
实训5.3 ref 与 out 参数
用 ref 修改调用方变量、用 out 返回多个结果。
ref 传入前需赋值;out 方法内必须赋值;两者都传递引用。
using System;
class Program
{
static void DoubleRef(ref int n)
{
n *= 2;
}
static bool TryDiv(int a, int b, out int result)
{
if (b == 0)
{
result = 0;
return false;
}
result = a / b;
return true;
}
static void Main()
{
int x = 21;
DoubleRef(ref x);
Console.WriteLine($"ref 翻倍后:{x}");
if (TryDiv(20, 4, out int q))
Console.WriteLine($"商:{q}");
}
}
实训5.4 递归与重载
用递归求阶乘;用方法重载实现不同参数的打印。
递归要有终止条件;重载按参数类型/个数区分。
using System;
class Program
{
static long Factorial(int n)
{
if (n <= 1) return 1;
return n * Factorial(n - 1);
}
static void Print(int value) => Console.WriteLine($"整数:{value}");
static void Print(string value) => Console.WriteLine($"字符串:{value}");
static void Main()
{
Console.WriteLine($"5! = {Factorial(5)}");
Print(42);
Print("Hello");
}
}
单元6 · 数组与集合
数组、List
- 数组:长度固定;Length 属性。
- List
: 动态数组,Add/Insert/Remove/IndexOf。 - Dictionary:键值对,TryGetValue 安全读取;LINQ 查询。
实训6.1 数组遍历求最值
声明 int[5] {12,45,7,89,33},遍历求最大值与平均值。
数组长度固定;Length 属性;遍历累加。
using System;
class Program
{
static void Main()
{
int[] arr = { 12, 45, 7, 89, 33 };
int max = arr[0], sum = 0;
foreach (int v in arr)
{
if (v > max) max = v;
sum += v;
}
double avg = (double)sum / arr.Length;
Console.WriteLine($"最大值:{max}");
Console.WriteLine($"平均值:{avg:F2}");
}
}
实训6.2 List 增删改查
创建 List
List
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> fruits = new List<string> { "苹果", "香蕉" };
fruits.Add("橙子");
fruits.Insert(0, "葡萄");
Console.WriteLine($"数量:{fruits.Count}");
fruits.Remove("香蕉");
foreach (string f in fruits)
Console.WriteLine(f);
Console.WriteLine($"橙子索引:{fruits.IndexOf("橙子")}");
}
}
实训6.3 Dictionary 键值对
用 Dictionary
Dictionary
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<string, int> ages = new Dictionary<string, int>
{
{ "张三", 20 },
{ "李四", 22 }
};
ages["王五"] = 24;
ages["李四"] = 23;
ages.Remove("王五");
foreach (var kv in ages)
Console.WriteLine($"{kv.Key}:{kv.Value} 岁");
if (ages.TryGetValue("张三", out int age))
Console.WriteLine($"张三的年龄:{age}");
}
}
实训6.4 LINQ 查询
用 LINQ 从成绩数组中筛选及格者、求平均值、按降序取前三。
LINQ 的 Where/OrderByDescending/Take/Average 链式查询。
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] scores = { 55, 90, 72, 88, 45, 98 };
var passed = scores.Where(s => s >= 60);
Console.WriteLine("及格:" + string.Join(", ", passed));
Console.WriteLine($"平均分:{scores.Average():F1}");
var top3 = scores.OrderByDescending(s => s).Take(3);
Console.WriteLine("前三:" + string.Join(", ", top3));
}
}
单元7 · 字符串与日期
字符串方法、StringBuilder、DateTime 处理
- 字符串:Trim/ToUpper/Replace/Split/Join。
- StringBuilder:大量拼接时避免多次拷贝。
- 日期正则:DateTime 格式化;Regex 校验提取。
实训7.1 字符串常用方法
对字符串 " Hello, C# " 去空格、转大小写、替换、拆分、拼接。
Trim/ToUpper/Replace/Split/Join 常用字符串方法。
using System;
class Program
{
static void Main()
{
string s = " Hello, C# ";
Console.WriteLine($"trim:|{s.Trim()}|");
Console.WriteLine($"大写:{s.Trim().ToUpper()}");
Console.WriteLine($"替换:{s.Trim().Replace("C#", "CSharp")}");
string[] parts = s.Trim().Split(',');
Console.WriteLine($"拆分:{string.Join(" | ", parts)}");
}
}
实训7.2 StringBuilder 高效拼接
用 StringBuilder 拼接 1 到 100 的数字序列,输出长度与结果前部。
StringBuilder 避免字符串不可变带来的多次拷贝。
using System;
using System.Text;
class Program
{
static void Main()
{
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 100; i++)
{
if (i > 1) sb.Append(",");
sb.Append(i);
}
string result = sb.ToString();
Console.WriteLine($"长度:{result.Length}");
Console.WriteLine($"前 20 字符:{result.Substring(0, 20)}...");
}
}
实训7.3 DateTime 日期处理
获取当前时间,输出年月日、星期,计算 30 天后的日期。
DateTime.Now;ToString 格式化;AddDays 加减日期。
using System;
class Program
{
static void Main()
{
DateTime now = DateTime.Now;
Console.WriteLine($"当前时间:{now:yyyy-MM-dd HH:mm:ss}");
Console.WriteLine($"今天是:{now:dddd}");
Console.WriteLine($"30 天后:{now.AddDays(30):yyyy-MM-dd}");
Console.WriteLine($"今年:{now.Year} 年");
}
}
实训7.4 正则表达式
用 Regex 校验邮箱格式并提取文本中的数字。
Regex.IsMatch 校验;Regex.Matches 提取全部匹配。
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string email = "user@example.com";
bool valid = Regex.IsMatch(email, @"^[\w.-]+@[\w.-]+\.\w+$");
Console.WriteLine($"邮箱格式:{(valid ? "正确" : "错误")}");
string text = "订单号 123,金额 45.6 元";
MatchCollection nums = Regex.Matches(text, @"\d+");
foreach (Match m in nums)
Console.WriteLine($"数字:{m.Value}");
}
}
单元8 · 面向对象
类、属性、继承、多态、接口
- 类:属性 { get; set; };构造器初始化。
- 继承:virtual/override 多态;base 调用基类。
- 接口:interface + 实现类;多态统一调用。
实训8.1 定义类与对象
定义 Student 类(Name、Score 属性,GetInfo 方法),实例化并调用。
class 定义类;属性 { get; set; };new 实例化。
using System;
class Student
{
public string Name { get; set; }
public double Score { get; set; }
public Student(string name, double score)
{
Name = name;
Score = score;
}
public string GetInfo()
{
return $"{Name},成绩 {Score} 分";
}
}
class Program
{
static void Main()
{
Student stu = new Student("小明", 92.5);
Console.WriteLine(stu.GetInfo());
}
}
实训8.2 继承与方法重写
定义 Animal 基类(Speak 虚方法)和 Dog 子类(重写),体现多态。
virtual 定义可重写方法;override 重写;base 调用基类。
using System;
class Animal
{
public virtual string Speak()
{
return "动物叫声";
}
}
class Dog : Animal
{
public override string Speak()
{
return base.Speak() + ":汪汪!";
}
}
class Program
{
static void Main()
{
Animal a = new Dog();
Console.WriteLine(a.Speak());
}
}
实训8.3 封装与属性校验
用私有字段 + 属性校验实现银行账户:存款、取款、查询余额。
属性 get/set 内做校验;private 封装数据。
using System;
class BankAccount
{
private decimal balance;
public decimal Balance => balance;
public void Deposit(decimal amount)
{
if (amount > 0)
balance += amount;
}
public bool Withdraw(decimal amount)
{
if (amount > 0 && amount <= balance)
{
balance -= amount;
return true;
}
return false;
}
}
class Program
{
static void Main()
{
BankAccount acc = new BankAccount();
acc.Deposit(1000);
acc.Withdraw(300);
Console.WriteLine($"余额:{acc.Balance} 元");
}
}
实训8.4 接口与多态
定义 IShape 接口(Area 方法),Circle 与 Square 实现,遍历计算总面积。
interface 定义契约;实现类提供方法;多态统一调用。
using System;
using System.Collections.Generic;
interface IShape
{
double Area();
}
class Circle : IShape
{
private double radius;
public Circle(double r) { radius = r; }
public double Area() => Math.PI * radius * radius;
}
class Square : IShape
{
private double side;
public Square(double s) { side = s; }
public double Area() => side * side;
}
class Program
{
static void Main()
{
List<IShape> shapes = new List<IShape>
{
new Circle(3),
new Square(5)
};
double total = 0;
foreach (IShape s in shapes)
total += s.Area();
Console.WriteLine($"总面积:{total:F2}");
}
}
单元9 · 异常处理
try/catch/finally、自定义异常、using 资源管理
- 异常:try/catch/finally 捕获与清理。
- 自定义:继承 Exception 定义领域异常。
- 资源:using 语句自动释放 IDisposable。
实训9.1 try/catch 捕获异常
模拟除零与数组越界异常,用 try/catch 捕获并输出错误信息。
try 包裹可能异常的代码;catch (Exception ex) 捕获;ex.Message 取信息。
using System;
class Program
{
static void Main()
{
try
{
int a = 10, b = 0;
Console.WriteLine(a / b);
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"除零异常:{ex.Message}");
}
try
{
int[] arr = { 1, 2, 3 };
Console.WriteLine(arr[10]);
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine($"越界异常:{ex.Message}");
}
}
}
实训9.2 多 catch 与 finally
依次捕获不同异常类型,finally 中输出清理信息。
catch 从具体到通用;finally 无论是否异常都执行。
using System;
class Program
{
static void Main()
{
try
{
Console.Write("输入数字:");
string input = Console.ReadLine();
int n = int.Parse(input);
Console.WriteLine(100 / n);
}
catch (DivideByZeroException)
{
Console.WriteLine("不能除以 0");
}
catch (FormatException)
{
Console.WriteLine("格式错误");
}
catch (Exception ex)
{
Console.WriteLine($"其他异常:{ex.Message}");
}
finally
{
Console.WriteLine("清理资源(总是执行)");
}
}
}
实训9.3 自定义异常
定义 ScoreOutOfRangeException 继承 Exception,在评级时抛出并捕获。
自定义异常继承 Exception 并调用 base 构造函数传消息。
using System;
class ScoreOutOfRangeException : Exception
{
public ScoreOutOfRangeException(string message) : base(message) { }
}
class Program
{
static string Grade(int score)
{
if (score < 0 || score > 100)
throw new ScoreOutOfRangeException($"非法分数:{score}");
if (score >= 90) return "优秀";
if (score >= 60) return "及格";
return "不及格";
}
static void Main()
{
try
{
Console.WriteLine(Grade(95));
Console.WriteLine(Grade(120));
}
catch (ScoreOutOfRangeException ex)
{
Console.WriteLine($"自定义异常:{ex.Message}");
}
}
}
实训9.4 using 资源释放
用 using 语句管理 StreamWriter 写文件,异常时也确保释放。
using 保证 IDisposable 资源在离开作用域时释放;等价于 try/finally Dispose。
using System;
using System.IO;
class Program
{
static void Main()
{
string file = "data.txt";
using (StreamWriter writer = new StreamWriter(file))
{
writer.WriteLine("第一行");
writer.WriteLine("第二行");
}
Console.WriteLine("写入完成,内容:");
Console.WriteLine(File.ReadAllText(file));
}
}
单元10 · LINQ 与委托
委托、Lambda、LINQ 查询语法与方法语法
- 委托:delegate 类型 + Lambda 简化。
- Func/Action:内置委托,Func 有返回值、Action 无。
- LINQ:Where/OrderBy/Select/GroupBy 链式查询。
实训10.1 委托基础
声明委托类型,实例化指向方法并调用;用匿名方法简化。
delegate 定义委托;委托变量可指向兼容签名的方法。
using System;
class Program
{
delegate int BinaryOp(int a, int b);
static int Add(int a, int b) => a + b;
static void Main()
{
BinaryOp op = Add;
Console.WriteLine($"委托调用:{op(3, 4)}");
BinaryOp multiply = (a, b) => a * b;
Console.WriteLine($"Lambda 委托:{multiply(3, 4)}");
}
}
实训10.2 Lambda 与内置委托
用 Func
Func 有返回值;Action 无返回值;Lambda 简化匿名方法。
using System;
class Program
{
static void Main()
{
Func<int, int, int> add = (a, b) => a + b;
Func<int, bool> isEven = n => n % 2 == 0;
Action<string> print = msg => Console.WriteLine(msg);
Console.WriteLine($"add(10, 20) = {add(10, 20)}");
Console.WriteLine($"6 是偶数:{isEven(6)}");
print("Action 输出");
}
}
实训10.3 LINQ 方法语法
用 LINQ 方法语法对学生集合按成绩排序、筛选、投影。
Where/OrderBy/Select 链式;ToList 物化结果。
using System;
using System.Collections.Generic;
using System.Linq;
class Student
{
public string Name { get; set; }
public int Score { get; set; }
}
class Program
{
static void Main()
{
List<Student> students = new List<Student>
{
new Student { Name = "张三", Score = 78 },
new Student { Name = "李四", Score = 92 },
new Student { Name = "王五", Score = 65 }
};
var top = students
.Where(s => s.Score >= 70)
.OrderByDescending(s => s.Score)
.Select(s => $"{s.Name}:{s.Score}");
foreach (var item in top)
Console.WriteLine(item);
}
}
实训10.4 LINQ 查询语法与分组
用查询语法分组统计各等级人数,输出结果。
from/where/group by 查询语法;group + Count() 统计。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
int[] scores = { 95, 72, 88, 45, 60, 33, 100 };
var groups = from s in scores
group s by (s >= 90 ? "优秀" : s >= 60 ? "及格" : "不及格") into g
select new { Grade = g.Key, Count = g.Count(), Average = g.Average() };
foreach (var g in groups)
Console.WriteLine($"{g.Grade}:{g.Count} 人,平均 {g.Average:F1}");
}
}
单元11 · 文件与异步编程
File 读写、async/await、Task
- 文件:File/Directory/FileInfo 便捷操作。
- 异步:async/await + Task;Task.WhenAll 并发。
- 并行:Parallel.For 并行循环,注意线程安全。
实训11.1 File 读写文件
用 File 类写入文本文件并读取输出。
File.WriteAllText / File.ReadAllText 简洁读写。
using System;
using System.IO;
class Program
{
static void Main()
{
string file = "notes.txt";
File.WriteAllText(file, "Hello C# File\n第二行");
string content = File.ReadAllText(file);
Console.WriteLine("文件内容:");
Console.WriteLine(content);
Console.WriteLine($"大小:{new FileInfo(file).Length} 字节");
}
}
实训11.2 目录与文件信息
列出指定目录下的文件与子目录,输出文件大小。
Directory.GetFiles / Directory.GetDirectories / FileInfo。
using System;
using System.IO;
class Program
{
static void Main()
{
string dir = "docs";
Directory.CreateDirectory(dir);
File.WriteAllText(Path.Combine(dir, "a.txt"), "A");
File.WriteAllText(Path.Combine(dir, "b.txt"), "B");
foreach (string file in Directory.GetFiles(dir))
{
FileInfo info = new FileInfo(file);
Console.WriteLine($"{info.Name}:{info.Length} 字节");
}
Console.WriteLine($"文件总数:{Directory.GetFiles(dir).Length}");
}
}
实训11.3 async/await 异步方法
用 async/await 模拟耗时任务:下载两个资源,并发执行并汇总。
async 方法返回 Task;await 等待异步操作;Task.WhenAll 并发。
using System;
using System.Threading.Tasks;
class Program
{
static async Task<string> FetchAsync(string name, int ms)
{
await Task.Delay(ms);
return $"{name} 完成";
}
static async Task Main()
{
Console.WriteLine("开始下载...");
var t1 = FetchAsync("资源A", 600);
var t2 = FetchAsync("资源B", 400);
string[] results = await Task.WhenAll(t1, t2);
foreach (var r in results)
Console.WriteLine(r);
Console.WriteLine("全部完成");
}
}
实训11.4 并行处理
用 Parallel.For 并行计算 1 到 1000000 的平方和(分段累加)。
Parallel.For 自动并行;Interlocked.Add 或锁保证累加安全。
using System;
using System.Threading.Tasks;
class Program
{
static void Main()
{
long sum = 0;
object lockObj = new object();
Parallel.For(1, 1000001, i =>
{
long sq = (long)i * i;
lock (lockObj)
{
sum += sq;
}
});
Console.WriteLine($"1 到 1000000 的平方和:{sum}");
}
}
单元12 · 综合项目实训
综合运用 C# 知识完成项目
- 综合:类、集合、LINQ、文件、异常组合使用。
- 工程化:方法封装、排序统计、格式化输出。
实训12.1 学生成绩管理系统
用 List
类 + List + LINQ 组合;OrderByDescending 排序;Average 均值。
using System;
using System.Collections.Generic;
using System.Linq;
class Student
{
public string Name { get; set; }
public double Chinese { get; set; }
public double Math { get; set; }
public double Average => (Chinese + Math) / 2;
}
class Program
{
static void Main()
{
List<Student> students = new List<Student>
{
new Student { Name = "张三", Chinese = 90, Math = 85 },
new Student { Name = "李四", Chinese = 78, Math = 92 },
new Student { Name = "王五", Chinese = 88, Math = 76 }
};
Console.WriteLine("姓名 语文 数学 平均");
foreach (Student s in students)
Console.WriteLine($"{s.Name} {s.Chinese} {s.Math} {s.Average:F1}");
Console.WriteLine($"全班平均分:{students.Average(s => s.Average):F1}");
var top = students.OrderByDescending(s => s.Average).First();
Console.WriteLine($"第一名:{top.Name}");
}
}
实训12.2 词频统计器
统计文本中单词出现次数,输出出现最多的单词。
Split 拆词;Dictionary
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
string text = "csharp is powerful csharp is fast csharp is fun";
string[] words = text.ToLower().Split(' ');
Dictionary<string, int> freq = new Dictionary<string, int>();
foreach (string w in words)
{
if (freq.ContainsKey(w))
freq[w]++;
else
freq[w] = 1;
}
var top = freq.OrderByDescending(kv => kv.Value).First();
Console.WriteLine("词频统计:");
foreach (var kv in freq)
Console.WriteLine($"{kv.Key}:{kv.Value}");
Console.WriteLine($"出现最多:{top.Key},{top.Value} 次");
}
}
实训12.3 通讯录管理
实现通讯录:联系人(姓名、电话、邮箱),支持添加、查找、删除并输出。
List
using System;
using System.Collections.Generic;
class Contact
{
public string Name { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
class AddressBook
{
private List<Contact> contacts = new List<Contact>();
public void Add(Contact c) => contacts.Add(c);
public Contact Find(string name) =>
contacts.Find(c => c.Name == name);
public bool Remove(string name)
{
int idx = contacts.FindIndex(c => c.Name == name);
if (idx == -1) return false;
contacts.RemoveAt(idx);
return true;
}
public void ListAll()
{
foreach (Contact c in contacts)
Console.WriteLine($"{c.Name} | {c.Phone} | {c.Email}");
}
}
class Program
{
static void Main()
{
AddressBook book = new AddressBook();
book.Add(new Contact { Name = "张三", Phone = "13800000001", Email = "a@x.com" });
book.Add(new Contact { Name = "李四", Phone = "13800000002", Email = "b@x.com" });
book.ListAll();
Contact c = book.Find("张三");
Console.WriteLine($"找到:{c?.Name},电话 {c?.Phone}");
Console.WriteLine($"删除李四:{book.Remove("李四")}");
book.ListAll();
}
}
实训12.4 购物车结算
用类实现购物车:商品添加、计算总价、按价格降序输出清单。
Cart 类 + List
using System;
using System.Collections.Generic;
using System.Linq;
class CartItem
{
public string Name { get; set; }
public double Price { get; set; }
public int Qty { get; set; }
public double Subtotal => Price * Qty;
}
class Cart
{
private List<CartItem> items = new List<CartItem>();
public void Add(CartItem item) => items.Add(item);
public double Total => items.Sum(i => i.Subtotal);
public void List()
{
foreach (CartItem i in items.OrderByDescending(i => i.Subtotal))
Console.WriteLine($"{i.Name} x{i.Qty} = {i.Subtotal:F2} 元");
}
}
class Program
{
static void Main()
{
Cart cart = new Cart();
cart.Add(new CartItem { Name = "C# 教程", Price = 59, Qty = 2 });
cart.Add(new CartItem { Name = "编程鼠标", Price = 129, Qty = 1 });
cart.List();
Console.WriteLine($"总计:{cart.Total:F2} 元");
}
}