1. 条件语句
1.1 if 语句
using System;
public class IfStatements
{
public static void Main()
{
// 基本 if 语句
int age = 18;
if (age >= 18)
{
Console.WriteLine("您已成年");
}
// if-else 语句
int score = 85;
if (score >= 90)
{
Console.WriteLine("优秀");
}
else if (score >= 80)
{
Console.WriteLine("良好");
}
else if (score >= 70)
{
Console.WriteLine("中等");
}
else if (score >= 60)
{
Console.WriteLine("及格");
}
else
{
Console.WriteLine("不及格");
}
// 嵌套 if 语句
bool isWeekend = true;
bool isRaining = false;
if (isWeekend)
{
if (isRaining)
{
Console.WriteLine("周末下雨,在家休息");
}
else
{
Console.WriteLine("周末晴天,出去游玩");
}
}
else
{
Console.WriteLine("工作日,正常上班");
}
// 逻辑运算符
DemonstrateLogicalOperators();
// 条件运算符(三元运算符)
DemonstrateTernaryOperator();
}
private static void DemonstrateLogicalOperators()
{
Console.WriteLine("\n=== 逻辑运算符演示 ===");
bool a = true;
bool b = false;
// 逻辑与 (&&) - 短路求值
Console.WriteLine($"a && b = {a && b}");
// 逻辑或 (||) - 短路求值
Console.WriteLine($"a || b = {a || b}");
// 逻辑非 (!)
Console.WriteLine($"!a = {!a}");
// 异或 (^)
Console.WriteLine($"a ^ b = {a ^ b}");
// 短路求值演示
int x = 5;
if (x > 0 && (x / x) > 0) // 第二个条件不会导致除零错误
{
Console.WriteLine("短路求值保护了除法运算");
}
// 复杂条件
int temperature = 25;
bool isSunny = true;
bool hasUmbrella = false;
if ((temperature > 20 && isSunny) || (temperature <= 20 && hasUmbrella))
{
Console.WriteLine("适合外出");
}
else
{
Console.WriteLine("不适合外出");
}
}
private static void DemonstrateTernaryOperator()
{
Console.WriteLine("\n=== 三元运算符演示 ===");
int number = 42;
// 基本三元运算符
string result = number > 0 ? "正数" : "非正数";
Console.WriteLine($"{number} 是 {result}");
// 嵌套三元运算符
string category = number > 0 ? (number % 2 == 0 ? "正偶数" : "正奇数") : "非正数";
Console.WriteLine($"{number} 是 {category}");
// 三元运算符 vs if-else
int a = 10, b = 20;
// 使用三元运算符
int max1 = a > b ? a : b;
// 使用 if-else
int max2;
if (a > b)
{
max2 = a;
}
else
{
max2 = b;
}
Console.WriteLine($"最大值: {max1} (三元运算符), {max2} (if-else)");
// 空合并运算符 (??)
string? nullableString = null;
string defaultValue = nullableString ?? "默认值";
Console.WriteLine($"空合并运算符结果: {defaultValue}");
// 空合并赋值运算符 (??=) - C# 8.0+
nullableString ??= "新赋值";
Console.WriteLine($"空合并赋值后: {nullableString}");
}
}
1.2 switch 语句
using System;
public class SwitchStatements
{
public static void Main()
{
// 传统 switch 语句
DemonstrateTraditionalSwitch();
// C# 8.0+ switch 表达式
DemonstrateSwitchExpressions();
// 模式匹配
DemonstratePatternMatching();
// 复杂模式匹配
DemonstrateAdvancedPatternMatching();
}
private static void DemonstrateTraditionalSwitch()
{
Console.WriteLine("=== 传统 Switch 语句 ===");
int dayOfWeek = 3;
switch (dayOfWeek)
{
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:
case 7:
Console.WriteLine("周末");
break;
default:
Console.WriteLine("无效的日期");
break;
}
// 字符串 switch
string grade = "A";
switch (grade.ToUpper())
{
case "A":
Console.WriteLine("优秀 (90-100)");
break;
case "B":
Console.WriteLine("良好 (80-89)");
break;
case "C":
Console.WriteLine("中等 (70-79)");
break;
case "D":
Console.WriteLine("及格 (60-69)");
break;
case "F":
Console.WriteLine("不及格 (0-59)");
break;
default:
Console.WriteLine("无效等级");
break;
}
// 枚举 switch
DayOfWeek today = DayOfWeek.Wednesday;
switch (today)
{
case DayOfWeek.Monday:
case DayOfWeek.Tuesday:
case DayOfWeek.Wednesday:
case DayOfWeek.Thursday:
case DayOfWeek.Friday:
Console.WriteLine("工作日");
break;
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
Console.WriteLine("周末");
break;
}
}
private static void DemonstrateSwitchExpressions()
{
Console.WriteLine("\n=== Switch 表达式 (C# 8.0+) ===");
// 基本 switch 表达式
int dayNumber = 3;
string dayName = dayNumber switch
{
1 => "星期一",
2 => "星期二",
3 => "星期三",
4 => "星期四",
5 => "星期五",
6 or 7 => "周末", // C# 9.0+ 逻辑模式
_ => "无效日期" // 默认情况
};
Console.WriteLine($"第 {dayNumber} 天是 {dayName}");
// 复杂 switch 表达式
var weather = (Temperature: 25, IsRaining: false, WindSpeed: 10);
string activity = weather switch
{
{ Temperature: > 30, IsRaining: false } => "游泳",
{ Temperature: > 20, IsRaining: false, WindSpeed: < 15 } => "户外运动",
{ Temperature: > 10, IsRaining: true } => "室内活动",
{ Temperature: <= 10 } => "在家休息",
_ => "待定"
};
Console.WriteLine($"今天适合: {activity}");
// 类型模式
object value = "Hello";
string description = value switch
{
int i => $"整数: {i}",
string s => $"字符串: {s}",
bool b => $"布尔值: {b}",
null => "空值",
_ => "未知类型"
};
Console.WriteLine(description);
}
private static void DemonstratePatternMatching()
{
Console.WriteLine("\n=== 模式匹配 ===");
// is 模式匹配
object obj = 42;
if (obj is int number)
{
Console.WriteLine($"这是一个整数: {number}");
}
if (obj is int n && n > 0)
{
Console.WriteLine($"这是一个正整数: {n}");
}
// 类型模式和属性模式
var person = new Person { Name = "张三", Age = 25 };
string message = person switch
{
{ Age: < 18 } => "未成年人",
{ Age: >= 18 and < 65 } => "成年人",
{ Age: >= 65 } => "老年人",
null => "无效对象"
};
Console.WriteLine($"{person.Name} 是 {message}");
// 位置模式(元组)
var point = (X: 3, Y: 4);
string quadrant = point switch
{
(0, 0) => "原点",
(var x, var y) when x > 0 && y > 0 => "第一象限",
(var x, var y) when x < 0 && y > 0 => "第二象限",
(var x, var y) when x < 0 && y < 0 => "第三象限",
(var x, var y) when x > 0 && y < 0 => "第四象限",
(var x, 0) when x != 0 => "X轴",
(0, var y) when y != 0 => "Y轴"
};
Console.WriteLine($"点 {point} 在 {quadrant}");
}
private static void DemonstrateAdvancedPatternMatching()
{
Console.WriteLine("\n=== 高级模式匹配 ===");
// 关系模式 (C# 9.0+)
int score = 85;
string grade = score switch
{
>= 90 => "A",
>= 80 => "B",
>= 70 => "C",
>= 60 => "D",
_ => "F"
};
Console.WriteLine($"分数 {score} 对应等级 {grade}");
// 逻辑模式 (C# 9.0+)
bool IsWorkingHour(int hour) => hour switch
{
>= 9 and <= 17 => true,
_ => false
};
Console.WriteLine($"10点是工作时间: {IsWorkingHour(10)}");
Console.WriteLine($"20点是工作时间: {IsWorkingHour(20)}");
// 否定模式 (C# 9.0+)
object value = null;
string result = value switch
{
not null => "有值",
null => "空值"
};
Console.WriteLine($"值状态: {result}");
// 嵌套模式
var order = new Order
{
Items = new[] { new OrderItem { Price = 100 }, new OrderItem { Price = 200 } },
Customer = new Customer { Type = CustomerType.Premium }
};
decimal discount = order switch
{
{ Customer.Type: CustomerType.Premium, Items.Length: > 1 } => 0.2m,
{ Customer.Type: CustomerType.Premium } => 0.1m,
{ Items.Length: > 5 } => 0.05m,
_ => 0m
};
Console.WriteLine($"订单折扣: {discount:P}");
}
}
// 辅助类
public class Person
{
public string Name { get; set; } = "";
public int Age { get; set; }
}
public class Order
{
public OrderItem[] Items { get; set; } = Array.Empty<OrderItem>();
public Customer Customer { get; set; } = new Customer();
}
public class OrderItem
{
public decimal Price { get; set; }
}
public class Customer
{
public CustomerType Type { get; set; }
}
public enum CustomerType
{
Regular,
Premium,
VIP
}
2. 循环语句
2.1 for 循环
using System;
using System.Collections.Generic;
public class ForLoops
{
public static void Main()
{
// 基本 for 循环
Console.WriteLine("=== 基本 for 循环 ===");
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"循环第 {i + 1} 次,i = {i}");
}
// 倒序循环
Console.WriteLine("\n倒序循环:");
for (int i = 5; i > 0; i--)
{
Console.WriteLine($"倒数第 {6 - i} 次,i = {i}");
}
// 步长不为1的循环
Console.WriteLine("\n步长为2的循环:");
for (int i = 0; i < 10; i += 2)
{
Console.WriteLine($"偶数索引: {i}");
}
// 多变量循环
Console.WriteLine("\n多变量循环:");
for (int i = 0, j = 10; i < j; i++, j--)
{
Console.WriteLine($"i = {i}, j = {j}");
}
// 无限循环(需要break跳出)
Console.WriteLine("\n条件循环:");
for (int i = 0; ; i++)
{
if (i >= 3)
break;
Console.WriteLine($"条件循环: {i}");
}
// 嵌套循环
DemonstrateNestedLoops();
// 循环控制语句
DemonstrateLoopControl();
}
private static void DemonstrateNestedLoops()
{
Console.WriteLine("\n=== 嵌套循环 ===");
// 打印乘法表
Console.WriteLine("九九乘法表:");
for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write($"{j}×{i}={i * j,2} ");
}
Console.WriteLine();
}
// 打印图案
Console.WriteLine("\n星号三角形:");
for (int i = 1; i <= 5; i++)
{
// 打印空格
for (int j = 1; j <= 5 - i; j++)
{
Console.Write(" ");
}
// 打印星号
for (int k = 1; k <= 2 * i - 1; k++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
private static void DemonstrateLoopControl()
{
Console.WriteLine("\n=== 循环控制语句 ===");
// break 语句
Console.WriteLine("break 示例:");
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
Console.WriteLine("遇到5,跳出循环");
break;
}
Console.WriteLine($"i = {i}");
}
// continue 语句
Console.WriteLine("\ncontinue 示例:");
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0)
{
continue; // 跳过偶数
}
Console.WriteLine($"奇数: {i}");
}
// 标签和 goto(不推荐使用)
Console.WriteLine("\n嵌套循环中的 break:");
bool found = false;
for (int i = 0; i < 3 && !found; i++)
{
for (int j = 0; j < 3; j++)
{
if (i == 1 && j == 1)
{
Console.WriteLine($"找到目标位置: ({i}, {j})");
found = true;
break; // 只跳出内层循环
}
Console.WriteLine($"检查位置: ({i}, {j})");
}
}
}
}
2.2 while 和 do-while 循环
using System;
public class WhileLoops
{
public static void Main()
{
// while 循环
DemonstrateWhileLoop();
// do-while 循环
DemonstrateDoWhileLoop();
// 实际应用示例
DemonstrateRealWorldExamples();
}
private static void DemonstrateWhileLoop()
{
Console.WriteLine("=== while 循环 ===");
// 基本 while 循环
int count = 0;
while (count < 5)
{
Console.WriteLine($"while 循环: count = {count}");
count++;
}
// 条件复杂的 while 循环
int number = 1;
int sum = 0;
while (sum < 100)
{
sum += number;
Console.WriteLine($"累加 {number},当前和为 {sum}");
number++;
}
// 无限循环(需要break)
Console.WriteLine("\n输入数字(输入0退出):");
while (true)
{
Console.Write("请输入: ");
string input = Console.ReadLine() ?? "";
if (int.TryParse(input, out int value))
{
if (value == 0)
{
Console.WriteLine("退出循环");
break;
}
Console.WriteLine($"您输入的数字是: {value}");
}
else
{
Console.WriteLine("请输入有效数字");
}
}
}
private static void DemonstrateDoWhileLoop()
{
Console.WriteLine("\n=== do-while 循环 ===");
// 基本 do-while 循环
int count = 0;
do
{
Console.WriteLine($"do-while 循环: count = {count}");
count++;
} while (count < 5);
// do-while 至少执行一次
Console.WriteLine("\ndo-while 至少执行一次的特性:");
int x = 10;
do
{
Console.WriteLine($"x = {x},条件为假但仍执行一次");
x++;
} while (x < 10); // 条件为假,但循环体已执行一次
// 菜单系统示例
DemonstrateMenuSystem();
}
private static void DemonstrateMenuSystem()
{
Console.WriteLine("\n=== 菜单系统示例 ===");
int choice;
do
{
Console.WriteLine("\n--- 主菜单 ---");
Console.WriteLine("1. 选项一");
Console.WriteLine("2. 选项二");
Console.WriteLine("3. 选项三");
Console.WriteLine("0. 退出");
Console.Write("请选择: ");
string input = Console.ReadLine() ?? "";
if (int.TryParse(input, out choice))
{
switch (choice)
{
case 1:
Console.WriteLine("执行选项一");
break;
case 2:
Console.WriteLine("执行选项二");
break;
case 3:
Console.WriteLine("执行选项三");
break;
case 0:
Console.WriteLine("再见!");
break;
default:
Console.WriteLine("无效选择,请重新输入");
choice = -1; // 继续循环
break;
}
}
else
{
Console.WriteLine("请输入数字");
choice = -1; // 继续循环
}
} while (choice != 0);
}
private static void DemonstrateRealWorldExamples()
{
Console.WriteLine("\n=== 实际应用示例 ===");
// 数字猜测游戏
PlayGuessingGame();
// 输入验证
ValidateInput();
}
private static void PlayGuessingGame()
{
Console.WriteLine("\n--- 数字猜测游戏 ---");
Random random = new Random();
int targetNumber = random.Next(1, 101);
int attempts = 0;
bool guessed = false;
Console.WriteLine("我想了一个1到100之间的数字,请猜猜是多少?");
while (!guessed)
{
Console.Write($"第 {attempts + 1} 次猜测: ");
string input = Console.ReadLine() ?? "";
if (int.TryParse(input, out int guess))
{
attempts++;
if (guess == targetNumber)
{
Console.WriteLine($"恭喜!您用 {attempts} 次猜中了数字 {targetNumber}!");
guessed = true;
}
else if (guess < targetNumber)
{
Console.WriteLine("太小了,请猜大一点");
}
else
{
Console.WriteLine("太大了,请猜小一点");
}
}
else
{
Console.WriteLine("请输入有效数字");
}
}
}
private static void ValidateInput()
{
Console.WriteLine("\n--- 输入验证示例 ---");
int age;
do
{
Console.Write("请输入您的年龄 (1-120): ");
string input = Console.ReadLine() ?? "";
if (int.TryParse(input, out age))
{
if (age >= 1 && age <= 120)
{
Console.WriteLine($"您的年龄是 {age} 岁");
break;
}
else
{
Console.WriteLine("年龄必须在1到120之间");
}
}
else
{
Console.WriteLine("请输入有效的数字");
}
} while (true);
}
}
2.3 foreach 循环
using System;
using System.Collections.Generic;
using System.Linq;
public class ForeachLoops
{
public static void Main()
{
// 数组遍历
DemonstrateArrayIteration();
// 集合遍历
DemonstrateCollectionIteration();
// 字符串遍历
DemonstrateStringIteration();
// 自定义可枚举类型
DemonstrateCustomEnumerable();
// foreach vs for 性能比较
ComparePerformance();
}
private static void DemonstrateArrayIteration()
{
Console.WriteLine("=== 数组遍历 ===");
int[] numbers = { 1, 2, 3, 4, 5 };
// foreach 遍历
Console.WriteLine("使用 foreach:");
foreach (int number in numbers)
{
Console.WriteLine($"数字: {number}");
}
// 多维数组遍历
int[,] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
Console.WriteLine("\n多维数组遍历:");
foreach (int value in matrix)
{
Console.Write($"{value} ");
}
Console.WriteLine();
// 锯齿数组遍历
int[][] jaggedArray = {
new int[] { 1, 2 },
new int[] { 3, 4, 5 },
new int[] { 6, 7, 8, 9 }
};
Console.WriteLine("\n锯齿数组遍历:");
foreach (int[] row in jaggedArray)
{
Console.Write("行: ");
foreach (int value in row)
{
Console.Write($"{value} ");
}
Console.WriteLine();
}
}
private static void DemonstrateCollectionIteration()
{
Console.WriteLine("\n=== 集合遍历 ===");
// List 遍历
var fruits = new List<string> { "苹果", "香蕉", "橙子", "葡萄" };
Console.WriteLine("水果列表:");
foreach (string fruit in fruits)
{
Console.WriteLine($"- {fruit}");
}
// Dictionary 遍历
var scores = new Dictionary<string, int>
{
{ "张三", 85 },
{ "李四", 92 },
{ "王五", 78 }
};
Console.WriteLine("\n成绩单:");
foreach (KeyValuePair<string, int> kvp in scores)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value} 分");
}
// 使用 var 简化
Console.WriteLine("\n使用 var 简化:");
foreach (var item in scores)
{
Console.WriteLine($"{item.Key}: {item.Value} 分");
}
// 只遍历键或值
Console.WriteLine("\n只遍历键:");
foreach (string name in scores.Keys)
{
Console.WriteLine($"学生: {name}");
}
Console.WriteLine("\n只遍历值:");
foreach (int score in scores.Values)
{
Console.WriteLine($"分数: {score}");
}
}
private static void DemonstrateStringIteration()
{
Console.WriteLine("\n=== 字符串遍历 ===");
string text = "Hello, World!";
Console.WriteLine($"字符串: {text}");
Console.WriteLine("字符分解:");
foreach (char c in text)
{
if (char.IsLetter(c))
{
Console.WriteLine($"字母: {c}");
}
else if (char.IsDigit(c))
{
Console.WriteLine($"数字: {c}");
}
else if (char.IsPunctuation(c))
{
Console.WriteLine($"标点: {c}");
}
else
{
Console.WriteLine($"其他: '{c}'");
}
}
// 统计字符
var charCount = new Dictionary<char, int>();
foreach (char c in text.ToLower())
{
if (char.IsLetter(c))
{
if (charCount.ContainsKey(c))
{
charCount[c]++;
}
else
{
charCount[c] = 1;
}
}
}
Console.WriteLine("\n字符统计:");
foreach (var item in charCount.OrderBy(x => x.Key))
{
Console.WriteLine($"'{item.Key}': {item.Value} 次");
}
}
private static void DemonstrateCustomEnumerable()
{
Console.WriteLine("\n=== 自定义可枚举类型 ===");
var range = new NumberRange(1, 5);
Console.WriteLine("自定义范围遍历:");
foreach (int number in range)
{
Console.WriteLine($"数字: {number}");
}
// 使用 yield 的简单示例
Console.WriteLine("\n斐波那契数列前10项:");
foreach (int fib in GetFibonacci(10))
{
Console.Write($"{fib} ");
}
Console.WriteLine();
}
private static void ComparePerformance()
{
Console.WriteLine("\n=== 性能比较 ===");
int[] largeArray = Enumerable.Range(1, 1000000).ToArray();
// foreach 性能测试
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
long sum1 = 0;
foreach (int number in largeArray)
{
sum1 += number;
}
stopwatch.Stop();
Console.WriteLine($"foreach 耗时: {stopwatch.ElapsedMilliseconds} ms, 和: {sum1}");
// for 性能测试
stopwatch.Restart();
long sum2 = 0;
for (int i = 0; i < largeArray.Length; i++)
{
sum2 += largeArray[i];
}
stopwatch.Stop();
Console.WriteLine($"for 耗时: {stopwatch.ElapsedMilliseconds} ms, 和: {sum2}");
// LINQ Sum 性能测试
stopwatch.Restart();
long sum3 = largeArray.Sum(x => (long)x);
stopwatch.Stop();
Console.WriteLine($"LINQ Sum 耗时: {stopwatch.ElapsedMilliseconds} ms, 和: {sum3}");
}
// 自定义可枚举类型
private static IEnumerable<int> GetFibonacci(int count)
{
int a = 0, b = 1;
for (int i = 0; i < count; i++)
{
yield return a;
(a, b) = (b, a + b);
}
}
}
// 自定义数字范围类
public class NumberRange : IEnumerable<int>
{
private readonly int _start;
private readonly int _end;
public NumberRange(int start, int end)
{
_start = start;
_end = end;
}
public IEnumerator<int> GetEnumerator()
{
for (int i = _start; i <= _end; i++)
{
yield return i;
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
3. 跳转语句
3.1 break 和 continue
using System;
using System.Collections.Generic;
public class JumpStatements
{
public static void Main()
{
// break 语句详解
DemonstrateBreak();
// continue 语句详解
DemonstrateContinue();
// 实际应用场景
DemonstrateRealWorldUsage();
}
private static void DemonstrateBreak()
{
Console.WriteLine("=== break 语句 ===");
// 在 for 循环中使用 break
Console.WriteLine("查找第一个偶数:");
int[] numbers = { 1, 3, 5, 8, 9, 12, 15 };
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] % 2 == 0)
{
Console.WriteLine($"找到第一个偶数: {numbers[i]},位置: {i}");
break; // 找到后立即退出循环
}
Console.WriteLine($"检查数字: {numbers[i]}");
}
// 在 while 循环中使用 break
Console.WriteLine("\n累加到超过100:");
int sum = 0;
int counter = 1;
while (true) // 无限循环
{
sum += counter;
Console.WriteLine($"累加 {counter},当前和: {sum}");
if (sum > 100)
{
Console.WriteLine("和超过100,退出循环");
break;
}
counter++;
}
// 在嵌套循环中使用 break
Console.WriteLine("\n嵌套循环中的 break:");
bool found = false;
for (int i = 1; i <= 3 && !found; i++)
{
Console.WriteLine($"外层循环: i = {i}");
for (int j = 1; j <= 3; j++)
{
Console.WriteLine($" 内层循环: j = {j}");
if (i * j == 6)
{
Console.WriteLine($" 找到乘积为6的组合: {i} × {j} = 6");
found = true;
break; // 只跳出内层循环
}
}
}
}
private static void DemonstrateContinue()
{
Console.WriteLine("\n=== continue 语句 ===");
// 在 for 循环中使用 continue
Console.WriteLine("打印1到10的奇数:");
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
continue; // 跳过偶数
}
Console.WriteLine($"奇数: {i}");
}
// 在 foreach 循环中使用 continue
Console.WriteLine("\n处理字符串列表(跳过空字符串):");
string[] words = { "Hello", "", "World", " ", "C#", null, "Programming" };
foreach (string word in words)
{
if (string.IsNullOrWhiteSpace(word))
{
Console.WriteLine("跳过空字符串或null");
continue;
}
Console.WriteLine($"处理单词: {word}");
}
// 在 while 循环中使用 continue
Console.WriteLine("\n输入处理(输入'skip'跳过,'quit'退出):");
while (true)
{
Console.Write("请输入: ");
string input = Console.ReadLine() ?? "";
if (input.ToLower() == "quit")
{
Console.WriteLine("退出程序");
break;
}
if (input.ToLower() == "skip")
{
Console.WriteLine("跳过此次输入");
continue;
}
Console.WriteLine($"您输入了: {input}");
}
}
private static void DemonstrateRealWorldUsage()
{
Console.WriteLine("\n=== 实际应用场景 ===");
// 数据验证和处理
ProcessStudentScores();
// 文件处理模拟
ProcessFiles();
// 游戏循环模拟
GameLoop();
}
private static void ProcessStudentScores()
{
Console.WriteLine("\n--- 学生成绩处理 ---");
var studentScores = new Dictionary<string, int[]>
{
{ "张三", new int[] { 85, 92, 78, 96 } },
{ "李四", new int[] { 88, 76, 94, 82 } },
{ "王五", new int[] { 92, 88, 90, 94 } },
{ "赵六", new int[] { 65, 70, 68, 72 } }
};
foreach (var student in studentScores)
{
string name = student.Key;
int[] scores = student.Value;
Console.WriteLine($"\n处理学生: {name}");
double total = 0;
int validScores = 0;
foreach (int score in scores)
{
// 跳过无效成绩
if (score < 0 || score > 100)
{
Console.WriteLine($" 跳过无效成绩: {score}");
continue;
}
total += score;
validScores++;
Console.WriteLine($" 有效成绩: {score}");
}
if (validScores == 0)
{
Console.WriteLine($" {name} 没有有效成绩");
continue;
}
double average = total / validScores;
Console.WriteLine($" {name} 的平均成绩: {average:F2}");
// 如果平均分低于70,标记为需要关注
if (average < 70)
{
Console.WriteLine($" ⚠️ {name} 需要额外关注(平均分低于70)");
}
}
}
private static void ProcessFiles()
{
Console.WriteLine("\n--- 文件处理模拟 ---");
string[] files = {
"document.txt",
"image.jpg",
"corrupted.dat",
"report.pdf",
"empty.txt",
"large_file.zip"
};
foreach (string file in files)
{
Console.WriteLine($"\n处理文件: {file}");
// 模拟文件检查
if (file.Contains("corrupted"))
{
Console.WriteLine(" 文件已损坏,跳过处理");
continue;
}
if (file.Contains("empty"))
{
Console.WriteLine(" 文件为空,跳过处理");
continue;
}
if (file.Contains("large"))
{
Console.WriteLine(" 文件过大,需要特殊处理");
// 这里可以调用特殊处理逻辑
Console.WriteLine(" 开始特殊处理...");
// 模拟处理时间
for (int i = 0; i < 3; i++)
{
Console.WriteLine($" 处理进度: {(i + 1) * 33}%");
if (i == 1) // 模拟处理中断
{
Console.WriteLine(" 处理中断,跳过剩余步骤");
break;
}
}
continue;
}
// 正常文件处理
Console.WriteLine(" 文件处理成功");
}
}
private static void GameLoop()
{
Console.WriteLine("\n--- 游戏循环模拟 ---");
int playerHealth = 100;
int level = 1;
bool gameRunning = true;
while (gameRunning)
{
Console.WriteLine($"\n=== 第 {level} 关 ===");
Console.WriteLine($"玩家生命值: {playerHealth}");
// 模拟关卡事件
Random random = new Random();
int eventType = random.Next(1, 5);
switch (eventType)
{
case 1:
Console.WriteLine("遇到敌人!");
int damage = random.Next(10, 31);
playerHealth -= damage;
Console.WriteLine($"受到 {damage} 点伤害");
if (playerHealth <= 0)
{
Console.WriteLine("游戏结束!");
gameRunning = false;
break; // 跳出 switch,然后退出 while 循环
}
break;
case 2:
Console.WriteLine("找到治疗药水!");
int healing = random.Next(15, 26);
playerHealth = Math.Min(100, playerHealth + healing);
Console.WriteLine($"恢复 {healing} 点生命值");
break;
case 3:
Console.WriteLine("发现陷阱,但成功避开了");
break;
case 4:
Console.WriteLine("什么都没发生");
break;
}
// 检查是否继续游戏
if (!gameRunning)
{
break;
}
level++;
// 模拟玩家选择
if (level > 5)
{
Console.WriteLine("恭喜通关!");
break;
}
Console.WriteLine("按任意键继续下一关...");
Console.ReadKey();
}
Console.WriteLine($"\n最终结果: 到达第 {level} 关,剩余生命值: {Math.Max(0, playerHealth)}");
}
}
3.2 return 语句
using System;
using System.Collections.Generic;
public class ReturnStatements
{
public static void Main()
{
// 基本 return 用法
DemonstrateBasicReturn();
// 多个返回点
DemonstrateMultipleReturns();
// 早期返回模式
DemonstrateEarlyReturn();
// 返回值类型
DemonstrateReturnTypes();
}
private static void DemonstrateBasicReturn()
{
Console.WriteLine("=== 基本 return 用法 ===");
// void 方法中的 return
PrintNumbers(5);
// 有返回值的方法
int sum = CalculateSum(1, 10);
Console.WriteLine($"1到10的和: {sum}");
// 条件返回
string result = GetGrade(85);
Console.WriteLine($"85分对应等级: {result}");
}
private static void PrintNumbers(int count)
{
Console.WriteLine($"打印前 {count} 个数字:");
for (int i = 1; i <= count; i++)
{
if (i > 10) // 限制最多打印10个
{
Console.WriteLine("达到最大限制,停止打印");
return; // 提前退出方法
}
Console.Write($"{i} ");
}
Console.WriteLine("\n打印完成");
}
private static int CalculateSum(int start, int end)
{
if (start > end)
{
Console.WriteLine("起始值不能大于结束值");
return 0; // 错误情况下返回默认值
}
int sum = 0;
for (int i = start; i <= end; i++)
{
sum += i;
}
return sum;
}
private static string GetGrade(int score)
{
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
if (score >= 60) return "D";
return "F";
}
private static (int Min, int Max, double Average) GetStatistics(int[] numbers)
{
if (numbers == null || numbers.Length == 0)
{
return (0, 0, 0);
}
int min = numbers[0];
int max = numbers[0];
long sum = 0;
foreach (int number in numbers)
{
if (number < min) min = number;
if (number > max) max = number;
sum += number;
}
return (min, max, (double)sum / numbers.Length);
}
}
3.3 goto 语句(不推荐使用)
using System;
public class GotoStatements
{
public static void Main()
{
Console.WriteLine("=== goto 语句示例(不推荐使用) ===");
// 基本 goto 用法
DemonstrateBasicGoto();
// goto 的替代方案
DemonstrateAlternatives();
}
private static void DemonstrateBasicGoto()
{
Console.WriteLine("\n--- 基本 goto 示例 ---");
int i = 0;
start:
Console.WriteLine($"i = {i}");
i++;
if (i < 3)
{
goto start; // 跳转到标签
}
Console.WriteLine("循环结束");
// goto 跳出嵌套循环
Console.WriteLine("\n--- 跳出嵌套循环 ---");
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
Console.WriteLine($"({x}, {y})");
if (x == 1 && y == 1)
{
Console.WriteLine("跳出所有循环");
goto end;
}
}
}
end:
Console.WriteLine("嵌套循环结束");
}
private static void DemonstrateAlternatives()
{
Console.WriteLine("\n--- goto 的替代方案 ---");
// 使用 break 和标志变量替代 goto
Console.WriteLine("使用标志变量:");
bool shouldExit = false;
for (int x = 0; x < 3 && !shouldExit; x++)
{
for (int y = 0; y < 3; y++)
{
Console.WriteLine($"({x}, {y})");
if (x == 1 && y == 1)
{
Console.WriteLine("跳出所有循环");
shouldExit = true;
break;
}
}
}
// 使用方法提取替代 goto
Console.WriteLine("\n使用方法提取:");
ProcessMatrix();
}
private static void ProcessMatrix()
{
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
Console.WriteLine($"({x}, {y})");
if (x == 1 && y == 1)
{
Console.WriteLine("找到目标,退出处理");
return; // 直接退出方法
}
}
}
}
}
4. 实践练习
4.1 综合练习:学生成绩管理系统
using System;
using System.Collections.Generic;
using System.Linq;
public class StudentGradeManager
{
private static Dictionary<string, List<int>> studentGrades = new Dictionary<string, List<int>>();
public static void Main()
{
Console.WriteLine("=== 学生成绩管理系统 ===");
bool running = true;
while (running)
{
ShowMenu();
string choice = Console.ReadLine() ?? "";
switch (choice)
{
case "1":
AddStudent();
break;
case "2":
AddGrade();
break;
case "3":
ShowStudentGrades();
break;
case "4":
ShowAllStudents();
break;
case "5":
ShowStatistics();
break;
case "6":
FindTopStudents();
break;
case "0":
Console.WriteLine("再见!");
running = false;
break;
default:
Console.WriteLine("无效选择,请重新输入");
break;
}
if (running)
{
Console.WriteLine("\n按任意键继续...");
Console.ReadKey();
Console.Clear();
}
}
}
private static void ShowMenu()
{
Console.WriteLine("\n--- 主菜单 ---");
Console.WriteLine("1. 添加学生");
Console.WriteLine("2. 添加成绩");
Console.WriteLine("3. 查看学生成绩");
Console.WriteLine("4. 显示所有学生");
Console.WriteLine("5. 显示统计信息");
Console.WriteLine("6. 查找优秀学生");
Console.WriteLine("0. 退出");
Console.Write("请选择: ");
}
private static void AddStudent()
{
Console.WriteLine("\n--- 添加学生 ---");
while (true)
{
Console.Write("请输入学生姓名(输入'back'返回): ");
string name = Console.ReadLine() ?? "";
if (name.ToLower() == "back")
{
return;
}
if (string.IsNullOrWhiteSpace(name))
{
Console.WriteLine("姓名不能为空,请重新输入");
continue;
}
if (studentGrades.ContainsKey(name))
{
Console.WriteLine($"学生 {name} 已存在");
continue;
}
studentGrades[name] = new List<int>();
Console.WriteLine($"学生 {name} 添加成功");
break;
}
}
private static void AddGrade()
{
Console.WriteLine("\n--- 添加成绩 ---");
if (studentGrades.Count == 0)
{
Console.WriteLine("没有学生记录,请先添加学生");
return;
}
// 显示所有学生
Console.WriteLine("现有学生:");
int index = 1;
foreach (string name in studentGrades.Keys)
{
Console.WriteLine($"{index}. {name}");
index++;
}
Console.Write("请输入学生姓名: ");
string studentName = Console.ReadLine() ?? "";
if (!studentGrades.ContainsKey(studentName))
{
Console.WriteLine("学生不存在");
return;
}
while (true)
{
Console.Write("请输入成绩 (0-100,输入-1结束): ");
string input = Console.ReadLine() ?? "";
if (!int.TryParse(input, out int grade))
{
Console.WriteLine("请输入有效数字");
continue;
}
if (grade == -1)
{
break;
}
if (grade < 0 || grade > 100)
{
Console.WriteLine("成绩必须在0-100之间");
continue;
}
studentGrades[studentName].Add(grade);
Console.WriteLine($"成绩 {grade} 添加成功");
}
}
private static void ShowStudentGrades()
{
Console.WriteLine("\n--- 查看学生成绩 ---");
if (studentGrades.Count == 0)
{
Console.WriteLine("没有学生记录");
return;
}
Console.Write("请输入学生姓名: ");
string name = Console.ReadLine() ?? "";
if (!studentGrades.ContainsKey(name))
{
Console.WriteLine("学生不存在");
return;
}
var grades = studentGrades[name];
if (grades.Count == 0)
{
Console.WriteLine($"{name} 还没有成绩记录");
return;
}
Console.WriteLine($"\n{name} 的成绩:");
for (int i = 0; i < grades.Count; i++)
{
Console.WriteLine($"第 {i + 1} 次: {grades[i]} 分");
}
double average = grades.Average();
int highest = grades.Max();
int lowest = grades.Min();
Console.WriteLine($"\n统计信息:");
Console.WriteLine($"平均分: {average:F2}");
Console.WriteLine($"最高分: {highest}");
Console.WriteLine($"最低分: {lowest}");
Console.WriteLine($"总次数: {grades.Count}");
}
private static void ShowAllStudents()
{
Console.WriteLine("\n--- 所有学生信息 ---");
if (studentGrades.Count == 0)
{
Console.WriteLine("没有学生记录");
return;
}
foreach (var student in studentGrades)
{
string name = student.Key;
var grades = student.Value;
Console.WriteLine($"\n学生: {name}");
if (grades.Count == 0)
{
Console.WriteLine(" 暂无成绩");
continue;
}
Console.WriteLine($" 成绩: [{string.Join(", ", grades)}]");
Console.WriteLine($" 平均分: {grades.Average():F2}");
Console.WriteLine($" 考试次数: {grades.Count}");
}
}
private static void ShowStatistics()
{
Console.WriteLine("\n--- 统计信息 ---");
if (studentGrades.Count == 0)
{
Console.WriteLine("没有学生记录");
return;
}
int totalStudents = studentGrades.Count;
int studentsWithGrades = 0;
var allGrades = new List<int>();
foreach (var grades in studentGrades.Values)
{
if (grades.Count > 0)
{
studentsWithGrades++;
allGrades.AddRange(grades);
}
}
Console.WriteLine($"总学生数: {totalStudents}");
Console.WriteLine($"有成绩的学生数: {studentsWithGrades}");
if (allGrades.Count == 0)
{
Console.WriteLine("暂无成绩数据");
return;
}
Console.WriteLine($"总成绩记录数: {allGrades.Count}");
Console.WriteLine($"全体平均分: {allGrades.Average():F2}");
Console.WriteLine($"全体最高分: {allGrades.Max()}");
Console.WriteLine($"全体最低分: {allGrades.Min()}");
// 成绩分布
int excellent = allGrades.Count(g => g >= 90);
int good = allGrades.Count(g => g >= 80 && g < 90);
int average = allGrades.Count(g => g >= 70 && g < 80);
int pass = allGrades.Count(g => g >= 60 && g < 70);
int fail = allGrades.Count(g => g < 60);
Console.WriteLine("\n成绩分布:");
Console.WriteLine($"优秀 (90-100): {excellent} 次 ({(double)excellent / allGrades.Count * 100:F1}%)");
Console.WriteLine($"良好 (80-89): {good} 次 ({(double)good / allGrades.Count * 100:F1}%)");
Console.WriteLine($"中等 (70-79): {average} 次 ({(double)average / allGrades.Count * 100:F1}%)");
Console.WriteLine($"及格 (60-69): {pass} 次 ({(double)pass / allGrades.Count * 100:F1}%)");
Console.WriteLine($"不及格 (<60): {fail} 次 ({(double)fail / allGrades.Count * 100:F1}%)");
}
private static void FindTopStudents()
{
Console.WriteLine("\n--- 优秀学生查找 ---");
if (studentGrades.Count == 0)
{
Console.WriteLine("没有学生记录");
return;
}
var studentsWithAverage = new List<(string Name, double Average)>();
foreach (var student in studentGrades)
{
if (student.Value.Count > 0)
{
double avg = student.Value.Average();
studentsWithAverage.Add((student.Key, avg));
}
}
if (studentsWithAverage.Count == 0)
{
Console.WriteLine("没有学生有成绩记录");
return;
}
// 按平均分排序
studentsWithAverage.Sort((a, b) => b.Average.CompareTo(a.Average));
Console.WriteLine("学生排名(按平均分):");
for (int i = 0; i < studentsWithAverage.Count; i++)
{
var student = studentsWithAverage[i];
string rank = GetRankSuffix(i + 1);
string grade = GetGradeLevel(student.Average);
Console.WriteLine($"{i + 1}{rank}: {student.Name} - 平均分: {student.Average:F2} ({grade})");
}
// 显示优秀学生(平均分>=85)
var excellentStudents = studentsWithAverage.Where(s => s.Average >= 85).ToList();
if (excellentStudents.Count > 0)
{
Console.WriteLine("\n🏆 优秀学生(平均分≥85):");
foreach (var student in excellentStudents)
{
Console.WriteLine($" {student.Name}: {student.Average:F2} 分");
}
}
else
{
Console.WriteLine("\n暂无优秀学生(平均分≥85)");
}
}
private static string GetRankSuffix(int rank)
{
return rank switch
{
1 => "st",
2 => "nd",
3 => "rd",
_ => "th"
};
}
private static string GetGradeLevel(double average)
{
return average switch
{
>= 90 => "优秀",
>= 80 => "良好",
>= 70 => "中等",
>= 60 => "及格",
_ => "不及格"
};
}
}
4.2 练习:数字游戏集合
using System;
using System.Collections.Generic;
using System.Linq;
public class NumberGames
{
public static void Main()
{
Console.WriteLine("=== 数字游戏集合 ===");
bool playing = true;
while (playing)
{
ShowGameMenu();
string choice = Console.ReadLine() ?? "";
switch (choice)
{
case "1":
PlayGuessingGame();
break;
case "2":
PlayNumberPattern();
break;
case "3":
PlayPrimeChecker();
break;
case "4":
PlayFibonacci();
break;
case "5":
PlayCalculator();
break;
case "0":
Console.WriteLine("感谢游玩!");
playing = false;
break;
default:
Console.WriteLine("无效选择,请重新输入");
break;
}
if (playing)
{
Console.WriteLine("\n按任意键返回主菜单...");
Console.ReadKey();
Console.Clear();
}
}
}
private static void ShowGameMenu()
{
Console.WriteLine("\n--- 游戏菜单 ---");
Console.WriteLine("1. 数字猜测游戏");
Console.WriteLine("2. 数字模式识别");
Console.WriteLine("3. 质数检查器");
Console.WriteLine("4. 斐波那契数列");
Console.WriteLine("5. 简单计算器");
Console.WriteLine("0. 退出");
Console.Write("请选择游戏: ");
}
private static void PlayGuessingGame()
{
Console.WriteLine("\n=== 数字猜测游戏 ===");
Console.WriteLine("我想了一个1到100之间的数字,请猜猜是多少?");
Random random = new Random();
int targetNumber = random.Next(1, 101);
int attempts = 0;
int maxAttempts = 7;
bool won = false;
while (attempts < maxAttempts && !won)
{
Console.Write($"第 {attempts + 1}/{maxAttempts} 次猜测: ");
string input = Console.ReadLine() ?? "";
if (!int.TryParse(input, out int guess))
{
Console.WriteLine("请输入有效数字");
continue;
}
attempts++;
if (guess == targetNumber)
{
Console.WriteLine($"🎉 恭喜!您用 {attempts} 次猜中了数字 {targetNumber}!");
won = true;
}
else if (guess < targetNumber)
{
int diff = targetNumber - guess;
if (diff <= 5)
{
Console.WriteLine("很接近了!太小了,请猜大一点");
}
else
{
Console.WriteLine("太小了,请猜大一点");
}
}
else
{
int diff = guess - targetNumber;
if (diff <= 5)
{
Console.WriteLine("很接近了!太大了,请猜小一点");
}
else
{
Console.WriteLine("太大了,请猜小一点");
}
}
}
if (!won)
{
Console.WriteLine($"😞 游戏结束!正确答案是 {targetNumber}");
}
}
private static void PlayNumberPattern()
{
Console.WriteLine("\n=== 数字模式识别 ===");
var patterns = new[]
{
new { Sequence = new[] { 2, 4, 6, 8 }, Next = 10, Description = "偶数序列" },
new { Sequence = new[] { 1, 4, 9, 16 }, Next = 25, Description = "平方数序列" },
new { Sequence = new[] { 1, 1, 2, 3, 5 }, Next = 8, Description = "斐波那契序列" },
new { Sequence = new[] { 3, 6, 12, 24 }, Next = 48, Description = "倍数序列" },
new { Sequence = new[] { 1, 3, 6, 10 }, Next = 15, Description = "三角数序列" }
};
Random random = new Random();
var pattern = patterns[random.Next(patterns.Length)];
Console.WriteLine("请找出下面数字序列的规律,并说出下一个数字:");
Console.WriteLine($"序列: {string.Join(", ", pattern.Sequence)}, ?");
int attempts = 0;
bool correct = false;
while (attempts < 3 && !correct)
{
Console.Write($"第 {attempts + 1}/3 次尝试: ");
string input = Console.ReadLine() ?? "";
if (!int.TryParse(input, out int guess))
{
Console.WriteLine("请输入有效数字");
continue;
}
attempts++;
if (guess == pattern.Next)
{
Console.WriteLine($"🎉 正确!这是 {pattern.Description}");
correct = true;
}
else
{
if (attempts < 3)
{
Console.WriteLine("不正确,请再试一次");
}
else
{
Console.WriteLine($"😞 正确答案是 {pattern.Next},这是 {pattern.Description}");
}
}
}
}
private static void PlayPrimeChecker()
{
Console.WriteLine("\n=== 质数检查器 ===");
Console.WriteLine("输入数字,我来判断是否为质数(输入0退出)");
while (true)
{
Console.Write("请输入数字: ");
string input = Console.ReadLine() ?? "";
if (!int.TryParse(input, out int number))
{
Console.WriteLine("请输入有效数字");
continue;
}
if (number == 0)
{
break;
}
if (number < 2)
{
Console.WriteLine($"{number} 不是质数(质数必须大于1)");
continue;
}
bool isPrime = IsPrime(number);
if (isPrime)
{
Console.WriteLine($"✅ {number} 是质数");
// 显示附近的质数
var nearbyPrimes = FindNearbyPrimes(number, 5);
if (nearbyPrimes.Count > 1)
{
Console.WriteLine($"附近的质数: {string.Join(", ", nearbyPrimes)}");
}
}
else
{
Console.WriteLine($"❌ {number} 不是质数");
// 显示因数分解
var factors = GetFactors(number);
Console.WriteLine($"因数: {string.Join(", ", factors)}");
}
}
}
private static bool IsPrime(int number)
{
if (number < 2) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
for (int i = 3; i * i <= number; i += 2)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
private static List<int> FindNearbyPrimes(int center, int count)
{
var primes = new List<int>();
// 向前查找
for (int i = center - 1; i >= 2 && primes.Count < count / 2; i--)
{
if (IsPrime(i))
{
primes.Insert(0, i);
}
}
// 添加中心数字(如果是质数)
if (IsPrime(center))
{
primes.Add(center);
}
// 向后查找
for (int i = center + 1; primes.Count < count; i++)
{
if (IsPrime(i))
{
primes.Add(i);
}
}
return primes;
}
private static List<int> GetFactors(int number)
{
var factors = new List<int>();
for (int i = 1; i <= number; i++)
{
if (number % i == 0)
{
factors.Add(i);
}
}
return factors;
}
private static void PlayFibonacci()
{
Console.WriteLine("\n=== 斐波那契数列 ===");
while (true)
{
Console.Write("请输入要生成的斐波那契数列长度(输入0退出): ");
string input = Console.ReadLine() ?? "";
if (!int.TryParse(input, out int count))
{
Console.WriteLine("请输入有效数字");
continue;
}
if (count == 0)
{
break;
}
if (count < 1)
{
Console.WriteLine("长度必须大于0");
continue;
}
Console.WriteLine($"\n前 {count} 个斐波那契数:");
long a = 0, b = 1;
for (int i = 0; i < count; i++)
{
if (i == 0)
{
Console.Write($"{a}");
}
else if (i == 1)
{
Console.Write($", {b}");
}
else
{
long next = a + b;
Console.Write($", {next}");
a = b;
b = next;
}
// 每10个数字换行
if ((i + 1) % 10 == 0)
{
Console.WriteLine();
}
}
Console.WriteLine();
// 显示黄金比例近似值
if (count >= 10)
{
double ratio = (double)b / a;
Console.WriteLine($"\n黄金比例近似值: {ratio:F6}");
Console.WriteLine($"实际黄金比例: {(1 + Math.Sqrt(5)) / 2:F6}");
}
}
}
private static void PlayCalculator()
{
Console.WriteLine("\n=== 简单计算器 ===");
Console.WriteLine("支持的运算: +, -, *, /, %, ^ (幂运算)");
Console.WriteLine("输入格式: 数字1 运算符 数字2");
Console.WriteLine("输入 'quit' 退出");
while (true)
{
Console.Write("\n请输入表达式: ");
string input = Console.ReadLine() ?? "";
if (input.ToLower() == "quit")
{
break;
}
string[] parts = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 3)
{
Console.WriteLine("格式错误,请使用: 数字1 运算符 数字2");
continue;
}
if (!double.TryParse(parts[0], out double num1))
{
Console.WriteLine("第一个数字格式错误");
continue;
}
if (!double.TryParse(parts[2], out double num2))
{
Console.WriteLine("第二个数字格式错误");
continue;
}
string op = parts[1];
double result = 0;
bool validOperation = true;
switch (op)
{
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 == 0)
{
Console.WriteLine("错误: 除数不能为零");
validOperation = false;
}
else
{
result = num1 / num2;
}
break;
case "%":
if (num2 == 0)
{
Console.WriteLine("错误: 除数不能为零");
validOperation = false;
}
else
{
result = num1 % num2;
}
break;
case "^":
result = Math.Pow(num1, num2);
break;
default:
Console.WriteLine($"不支持的运算符: {op}");
validOperation = false;
break;
}
if (validOperation)
{
Console.WriteLine($"结果: {num1} {op} {num2} = {result}");
// 显示额外信息
if (op == "/" && num1 % num2 != 0)
{
Console.WriteLine($"整数部分: {(int)(num1 / num2)}");
Console.WriteLine($"余数: {num1 % num2}");
}
}
}
}
}
5. 总结
本章详细介绍了C#中的控制结构与流程控制,包括:
5.1 条件语句
- if语句: 基本条件判断,支持嵌套和复杂逻辑
- switch语句: 多分支选择,包括传统switch和C# 8.0+的switch表达式
- 模式匹配: C# 7.0+引入的强大特性,支持类型模式、属性模式等
5.2 循环语句
- for循环: 适用于已知循环次数的情况
- while循环: 适用于条件驱动的循环
- do-while循环: 至少执行一次的循环
- foreach循环: 用于遍历集合和可枚举对象
5.3 跳转语句
- break: 跳出循环或switch语句
- continue: 跳过当前循环迭代
- return: 从方法返回值或控制权
- goto: 无条件跳转(不推荐使用)
5.4 最佳实践
- 优先使用早期返回模式,减少嵌套层次
- 合理使用switch表达式,提高代码可读性
- 避免使用goto语句,使用结构化控制流
- 在循环中合理使用break和continue,提高代码效率
- 利用模式匹配,编写更简洁的条件判断代码
5.5 性能考虑
- foreach通常比for循环更安全,性能差异很小
- switch语句在多分支情况下比多个if-else更高效
- 避免在循环中进行复杂计算,考虑提前计算或缓存
下一章我们将学习数组与集合,了解如何在C#中存储和操作数据集合。
private static void DemonstrateMultipleReturns()
{
Console.WriteLine("\n=== 多个返回点 ===");
// 测试不同的输入
TestDivision(10, 2);
TestDivision(10, 0);
TestDivision(-5, 2);
// 测试查找功能
int[] numbers = { 1, 3, 5, 7, 9, 11, 13 };
Console.WriteLine($"查找5: 索引 {FindNumber(numbers, 5)}");
Console.WriteLine($"查找8: 索引 {FindNumber(numbers, 8)}");
}
private static void TestDivision(double a, double b)
{
Console.WriteLine($"\n计算 {a} ÷ {b}:");
double result = SafeDivide(a, b);
if (!double.IsNaN(result))
{
Console.WriteLine($"结果: {result}");
}
}
private static double SafeDivide(double dividend, double divisor)
{
// 检查除数是否为零
if (divisor == 0)
{
Console.WriteLine("错误: 除数不能为零");
return double.NaN;
}
// 检查被除数是否为负数(假设业务规则不允许)
if (dividend < 0)
{
Console.WriteLine("警告: 被除数为负数");
return double.NaN;
}
// 正常计算
return dividend / divisor;
}
private static int FindNumber(int[] array, int target)
{
if (array == null)
{
Console.WriteLine("数组为空");
return -1;
}
for (int i = 0; i < array.Length; i++)
{
if (array[i] == target)
{
return i; // 找到目标,立即返回索引
}
}
return -1; // 未找到
}
private static void DemonstrateEarlyReturn()
{
Console.WriteLine("\n=== 早期返回模式 ===");
// 测试用户验证
ValidateUser("admin", "password123");
ValidateUser("", "password123");
ValidateUser("admin", "");
ValidateUser("user", "wrongpassword");
// 测试文件处理
ProcessFile("document.txt");
ProcessFile("large_file.zip");
ProcessFile("corrupted.dat");
}
private static bool ValidateUser(string username, string password)
{
Console.WriteLine($"\n验证用户: {username}");
// 早期返回 - 避免深层嵌套
if (string.IsNullOrEmpty(username))
{
Console.WriteLine("用户名不能为空");
return false;
}
if (string.IsNullOrEmpty(password))
{
Console.WriteLine("密码不能为空");
return false;
}
if (username.Length < 3)
{
Console.WriteLine("用户名长度至少3个字符");
return false;
}
if (password.Length < 8)
{
Console.WriteLine("密码长度至少8个字符");
return false;
}
// 模拟数据库验证
if (username != "admin" || password != "password123")
{
Console.WriteLine("用户名或密码错误");
return false;
}
Console.WriteLine("验证成功");
return true;
}
private static void ProcessFile(string filename)
{
Console.WriteLine($"\n处理文件: {filename}");
// 早期返回避免复杂的条件嵌套
if (string.IsNullOrEmpty(filename))
{
Console.WriteLine("文件名不能为空");
return;
}
if (filename.Contains("corrupted"))
{
Console.WriteLine("文件已损坏,无法处理");
return;
}
if (filename.Contains("large"))
{
Console.WriteLine("文件过大,需要特殊处理");
// 这里可以调用特殊处理逻辑
return;
}
// 正常处理逻辑
Console.WriteLine("文件处理成功");
}
private static void DemonstrateReturnTypes()
{
Console.WriteLine("\n=== 返回值类型 ===");
// 值类型返回
int number = GetRandomNumber();
Console.WriteLine($"随机数: {number}");
// 引用类型返回
string message = GetWelcomeMessage("张三");
Console.WriteLine(message);
// 集合返回
List<int> evenNumbers = GetEvenNumbers(1, 10);
Console.WriteLine($"偶数: [{string.Join(", ", evenNumbers)}]");
// 可空类型返回
int? result = TryParseInt("123");
Console.WriteLine($"解析结果: {result}");
result = TryParseInt("abc");
Console.WriteLine($"解析结果: {result ?? -1} (失败时显示-1)");
// 元组返回 (C# 7.0+)
var (min, max, avg) = GetStatistics(new[] { 1, 5, 3, 9, 2, 7 });
Console.WriteLine($"统计: 最小={min}, 最大={max}, 平均={avg:F2}");
}
private static int GetRandomNumber()
{
Random random = new Random();
return random.Next(1, 101);
}
private static string GetWelcomeMessage(string name)
{
if (string.IsNullOrEmpty(name))
{
return "欢迎访问!";
}
return $"欢迎您,{name}!";
}
private static List<int> GetEvenNumbers(int start, int end)
{
var result = new List<int>();
for (int i = start; i <= end; i++)
{
if (i % 2 == 0)
{
result.Add(i);
}
}
return result;
}
private static int? TryParseInt(string input)
{
if (int.TryParse(input, out int result))
{
return result;
}
return null;
}
private static (int Min, int Max, double Average) GetStatistics(int[] numbers)
{
if (numbers == null || numbers.Length == 0)
{
return (0, 0, 0);
}
int min = numbers[0];
int max = numbers[0];
long sum = 0;