Skip to content

C# 控制结构

本章将详细介绍 C# 中的控制结构,包括条件语句、循环语句和跳转语句,这些是程序流程控制的基础。

条件语句

if 语句

基本 if 语句

csharp
// 基本语法
if (condition)
{
    // 条件为真时执行的代码
}

// 示例
int age = 18;
if (age >= 18)
{
    Console.WriteLine("你已经成年了");
}

// 单行语句可以省略大括号(不推荐)
if (age >= 18)
    Console.WriteLine("你已经成年了");

if-else 语句

csharp
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 语句

csharp
int age = 25;
bool hasLicense = true;
bool hasInsurance = true;

if (age >= 18)
{
    if (hasLicense)
    {
        if (hasInsurance)
        {
            Console.WriteLine("可以开车");
        }
        else
        {
            Console.WriteLine("需要购买保险");
        }
    }
    else
    {
        Console.WriteLine("需要考取驾照");
    }
}
else
{
    Console.WriteLine("年龄不够");
}
```###
 switch 语句

#### 传统 switch 语句

```csharp
int dayOfWeek = 3;
string dayName;

switch (dayOfWeek)
{
    case 1:
        dayName = "星期一";
        break;
    case 2:
        dayName = "星期二";
        break;
    case 3:
        dayName = "星期三";
        break;
    case 4:
        dayName = "星期四";
        break;
    case 5:
        dayName = "星期五";
        break;
    case 6:
        dayName = "星期六";
        break;
    case 7:
        dayName = "星期日";
        break;
    default:
        dayName = "无效的日期";
        break;
}

Console.WriteLine($"今天是{dayName}");

switch 表达式 (C# 8.0+)

csharp
// 更简洁的 switch 表达式
int dayOfWeek = 3;
string dayName = dayOfWeek switch
{
    1 => "星期一",
    2 => "星期二",
    3 => "星期三",
    4 => "星期四",
    5 => "星期五",
    6 => "星期六",
    7 => "星期日",
    _ => "无效的日期"
};

Console.WriteLine($"今天是{dayName}");

// 复杂条件的 switch 表达式
string GetGrade(int score) => score switch
{
    >= 90 => "A",
    >= 80 => "B",
    >= 70 => "C",
    >= 60 => "D",
    _ => "F"
};

模式匹配 switch

csharp
object value = 42;

string result = value switch
{
    int i when i > 0 => $"正整数: {i}",
    int i when i < 0 => $"负整数: {i}",
    int => "零",
    string s => $"字符串: {s}",
    bool b => $"布尔值: {b}",
    null => "空值",
    _ => "未知类型"
};

Console.WriteLine(result);

循环语句

for 循环

基本 for 循环

csharp
// 基本语法: for (初始化; 条件; 迭代)
for (int i = 0; i < 5; i++)
{
    Console.WriteLine($"循环第 {i + 1} 次,i = {i}");
}

// 倒序循环
for (int i = 10; i >= 1; i--)
{
    Console.WriteLine($"倒计时: {i}");
}

// 步长为2的循环
for (int i = 0; i < 10; i += 2)
{
    Console.WriteLine($"偶数索引: {i}");
}

嵌套 for 循环

csharp
// 打印乘法表
Console.WriteLine("九九乘法表:");
for (int i = 1; i <= 9; i++)
{
    for (int j = 1; j <= i; j++)
    {
        Console.Write($"{j}×{i}={i * j}\t");
    }
    Console.WriteLine();
}

// 二维数组遍历
int[,] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int row = 0; row < matrix.GetLength(0); row++)
{
    for (int col = 0; col < matrix.GetLength(1); col++)
    {
        Console.Write($"{matrix[row, col]}\t");
    }
    Console.WriteLine();
}

while 循环

基本 while 循环

csharp
// 基本语法
int count = 0;
while (count < 5)
{
    Console.WriteLine($"count = {count}");
    count++;
}

// 用户输入验证
string input;
int number;
Console.WriteLine("请输入一个正整数:");
while (true)
{
    input = Console.ReadLine();
    if (int.TryParse(input, out number) && number > 0)
    {
        break;
    }
    Console.WriteLine("输入无效,请重新输入一个正整数:");
}
Console.WriteLine($"您输入的数字是: {number}");

do-while 循环

csharp
// 至少执行一次的循环
int attempts = 0;
string password;

do
{
    Console.Write("请输入密码: ");
    password = Console.ReadLine();
    attempts++;
    
    if (password != "123456")
    {
        Console.WriteLine("密码错误,请重试");
    }
} while (password != "123456" && attempts < 3);

if (password == "123456")
{
    Console.WriteLine("登录成功!");
}
else
{
    Console.WriteLine("尝试次数过多,账户被锁定");
}

foreach 循环

遍历数组

csharp
// 遍历整数数组
int[] numbers = {1, 2, 3, 4, 5};
foreach (int number in numbers)
{
    Console.WriteLine($"数字: {number}");
}

// 遍历字符串数组
string[] names = {"Alice", "Bob", "Charlie"};
foreach (string name in names)
{
    Console.WriteLine($"姓名: {name}");
}

// 遍历字符串中的字符
string text = "Hello";
foreach (char c in text)
{
    Console.WriteLine($"字符: {c}");
}

遍历集合

csharp
using System.Collections.Generic;

// 遍历 List
List<string> fruits = new List<string> {"苹果", "香蕉", "橙子"};
foreach (string fruit in fruits)
{
    Console.WriteLine($"水果: {fruit}");
}

// 遍历 Dictionary
Dictionary<string, int> scores = new Dictionary<string, int>
{
    {"Alice", 95},
    {"Bob", 87},
    {"Charlie", 92}
};

foreach (KeyValuePair<string, int> pair in scores)
{
    Console.WriteLine($"{pair.Key}: {pair.Value}分");
}

// 简化的 Dictionary 遍历
foreach (var (name, score) in scores)
{
    Console.WriteLine($"{name}: {score}分");
}

跳转语句

break 语句

csharp
// 在循环中使用 break
for (int i = 0; i < 10; i++)
{
    if (i == 5)
    {
        Console.WriteLine("遇到5,跳出循环");
        break;
    }
    Console.WriteLine($"i = {i}");
}

// 在嵌套循环中使用 break
bool found = false;
for (int i = 0; i < 5 && !found; i++)
{
    for (int j = 0; j < 5; j++)
    {
        if (i * j == 6)
        {
            Console.WriteLine($"找到了: {i} * {j} = 6");
            found = true;
            break;  // 只跳出内层循环
        }
    }
}

continue 语句

csharp
// 跳过偶数,只打印奇数
for (int i = 0; i < 10; i++)
{
    if (i % 2 == 0)
    {
        continue;  // 跳过本次循环的剩余部分
    }
    Console.WriteLine($"奇数: {i}");
}

// 处理数组,跳过负数
int[] numbers = {1, -2, 3, -4, 5, -6, 7};
foreach (int number in numbers)
{
    if (number < 0)
    {
        continue;
    }
    Console.WriteLine($"正数: {number}");
}

goto 语句(不推荐使用)

csharp
// goto 语句示例(仅作了解,实际开发中避免使用)
int choice = 2;

switch (choice)
{
    case 1:
        Console.WriteLine("选择了选项1");
        goto case 3;  // 跳转到 case 3
    case 2:
        Console.WriteLine("选择了选项2");
        goto default;  // 跳转到 default
    case 3:
        Console.WriteLine("执行选项3的代码");
        break;
    default:
        Console.WriteLine("默认处理");
        break;
}

// 使用标签的 goto(强烈不推荐)
int x = 1;
start:
Console.WriteLine($"x = {x}");
x++;
if (x <= 3)
    goto start;

return 语句

csharp
// 在方法中使用 return
static int FindFirstEven(int[] numbers)
{
    foreach (int number in numbers)
    {
        if (number % 2 == 0)
        {
            return number;  // 找到第一个偶数就返回
        }
    }
    return -1;  // 没找到偶数返回-1
}

// 在 Main 方法中使用 return
static int Main(string[] args)
{
    if (args.Length == 0)
    {
        Console.WriteLine("请提供命令行参数");
        return 1;  // 返回错误代码
    }
    
    Console.WriteLine($"第一个参数: {args[0]}");
    return 0;  // 返回成功代码
}

实践示例

示例 1:数字猜测游戏

csharp
using System;

class NumberGuessingGame
{
    static void Main()
    {
        Random random = new Random();
        int targetNumber = random.Next(1, 101);  // 1-100之间的随机数
        int attempts = 0;
        int maxAttempts = 7;
        bool hasWon = false;

        Console.WriteLine("=== 数字猜测游戏 ===");
        Console.WriteLine("我想了一个1到100之间的数字,你能猜出来吗?");
        Console.WriteLine($"你有{maxAttempts}次机会。");

        while (attempts < maxAttempts && !hasWon)
        {
            attempts++;
            Console.Write($"第{attempts}次猜测,请输入你的数字: ");
            
            string input = Console.ReadLine();
            if (!int.TryParse(input, out int guess))
            {
                Console.WriteLine("请输入有效的数字!");
                attempts--;  // 无效输入不计入尝试次数
                continue;
            }

            if (guess == targetNumber)
            {
                hasWon = true;
                Console.WriteLine($"🎉 恭喜你!猜对了!数字就是{targetNumber}");
                Console.WriteLine($"你用了{attempts}次就猜对了!");
            }
            else if (guess < targetNumber)
            {
                Console.WriteLine("太小了!试试更大的数字。");
            }
            else
            {
                Console.WriteLine("太大了!试试更小的数字。");
            }

            if (!hasWon && attempts < maxAttempts)
            {
                Console.WriteLine($"还剩{maxAttempts - attempts}次机会。");
            }
        }

        if (!hasWon)
        {
            Console.WriteLine($"😢 游戏结束!正确答案是{targetNumber}");
        }
    }
}

示例 2:简单菜单系统

csharp
using System;

class MenuSystem
{
    static void Main()
    {
        bool running = true;

        while (running)
        {
            ShowMenu();
            string choice = Console.ReadLine();

            switch (choice)
            {
                case "1":
                    ShowStudentInfo();
                    break;
                case "2":
                    CalculateGrade();
                    break;
                case "3":
                    ShowMultiplicationTable();
                    break;
                case "4":
                    Console.WriteLine("感谢使用,再见!");
                    running = false;
                    break;
                default:
                    Console.WriteLine("无效选择,请重新输入。");
                    break;
            }

            if (running)
            {
                Console.WriteLine("\n按任意键继续...");
                Console.ReadKey();
                Console.Clear();
            }
        }
    }

    static void ShowMenu()
    {
        Console.WriteLine("=== 学生管理系统 ===");
        Console.WriteLine("1. 显示学生信息");
        Console.WriteLine("2. 计算成绩等级");
        Console.WriteLine("3. 显示乘法表");
        Console.WriteLine("4. 退出程序");
        Console.Write("请选择功能 (1-4): ");
    }

    static void ShowStudentInfo()
    {
        Console.WriteLine("\n=== 学生信息 ===");
        string[] students = {"张三", "李四", "王五", "赵六"};
        int[] ages = {20, 19, 21, 20};

        for (int i = 0; i < students.Length; i++)
        {
            Console.WriteLine($"{i + 1}. 姓名: {students[i]}, 年龄: {ages[i]}");
        }
    }

    static void CalculateGrade()
    {
        Console.WriteLine("\n=== 成绩等级计算 ===");
        Console.Write("请输入成绩 (0-100): ");
        
        if (double.TryParse(Console.ReadLine(), out double score))
        {
            if (score < 0 || score > 100)
            {
                Console.WriteLine("成绩必须在0-100之间!");
                return;
            }

            string grade = score switch
            {
                >= 90 => "A (优秀)",
                >= 80 => "B (良好)",
                >= 70 => "C (中等)",
                >= 60 => "D (及格)",
                _ => "F (不及格)"
            };

            Console.WriteLine($"成绩: {score}, 等级: {grade}");
        }
        else
        {
            Console.WriteLine("请输入有效的数字!");
        }
    }

    static void ShowMultiplicationTable()
    {
        Console.WriteLine("\n=== 九九乘法表 ===");
        for (int i = 1; i <= 9; i++)
        {
            for (int j = 1; j <= i; j++)
            {
                Console.Write($"{j}×{i}={i * j:D2}  ");
            }
            Console.WriteLine();
        }
    }
}

示例 3:数组操作综合练习

csharp
using System;
using System.Linq;

class ArrayOperations
{
    static void Main()
    {
        // 初始化数组
        int[] numbers = {64, 34, 25, 12, 22, 11, 90, 88, 76, 50, 42};
        
        Console.WriteLine("原始数组:");
        PrintArray(numbers);
        
        // 查找最大值和最小值
        FindMinMax(numbers, out int min, out int max);
        Console.WriteLine($"\n最小值: {min}, 最大值: {max}");
        
        // 计算平均值
        double average = CalculateAverage(numbers);
        Console.WriteLine($"平均值: {average:F2}");
        
        // 查找特定值
        Console.Write("\n请输入要查找的数字: ");
        if (int.TryParse(Console.ReadLine(), out int target))
        {
            int index = FindNumber(numbers, target);
            if (index != -1)
            {
                Console.WriteLine($"数字 {target} 在索引 {index} 处找到");
            }
            else
            {
                Console.WriteLine($"数字 {target} 未找到");
            }
        }
        
        // 冒泡排序
        int[] sortedNumbers = (int[])numbers.Clone();
        BubbleSort(sortedNumbers);
        Console.WriteLine("\n排序后的数组:");
        PrintArray(sortedNumbers);
        
        // 统计偶数和奇数
        CountEvenOdd(numbers, out int evenCount, out int oddCount);
        Console.WriteLine($"\n偶数个数: {evenCount}, 奇数个数: {oddCount}");
    }
    
    static void PrintArray(int[] array)
    {
        foreach (int number in array)
        {
            Console.Write($"{number} ");
        }
        Console.WriteLine();
    }
    
    static void FindMinMax(int[] array, out int min, out int max)
    {
        min = max = array[0];
        
        for (int i = 1; i < array.Length; i++)
        {
            if (array[i] < min)
                min = array[i];
            if (array[i] > max)
                max = array[i];
        }
    }
    
    static double CalculateAverage(int[] array)
    {
        int sum = 0;
        foreach (int number in array)
        {
            sum += number;
        }
        return (double)sum / array.Length;
    }
    
    static int FindNumber(int[] array, int target)
    {
        for (int i = 0; i < array.Length; i++)
        {
            if (array[i] == target)
                return i;
        }
        return -1;
    }
    
    static void BubbleSort(int[] array)
    {
        int n = array.Length;
        for (int i = 0; i < n - 1; i++)
        {
            for (int j = 0; j < n - i - 1; j++)
            {
                if (array[j] > array[j + 1])
                {
                    // 交换元素
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
    }
    
    static void CountEvenOdd(int[] array, out int evenCount, out int oddCount)
    {
        evenCount = oddCount = 0;
        
        foreach (int number in array)
        {
            if (number % 2 == 0)
                evenCount++;
            else
                oddCount++;
        }
    }
}

性能考虑和最佳实践

循环优化

csharp
// 避免在循环中重复计算
// ❌ 不好的做法
for (int i = 0; i < array.Length; i++)  // 每次都计算 Length
{
    // 处理 array[i]
}

// ✅ 好的做法
int length = array.Length;
for (int i = 0; i < length; i++)
{
    // 处理 array[i]
}

// ✅ 更好的做法(如果不需要索引)
foreach (var item in array)
{
    // 处理 item
}

条件语句优化

csharp
// 将最可能的条件放在前面
if (mostLikelyCondition)
{
    // 最常执行的代码
}
else if (lessLikelyCondition)
{
    // 较少执行的代码
}
else
{
    // 最少执行的代码
}

// 使用 switch 表达式替代复杂的 if-else
string GetDayType(int day) => day switch
{
    1 or 2 or 3 or 4 or 5 => "工作日",
    6 or 7 => "周末",
    _ => "无效日期"
};

本章小结

本章详细介绍了 C# 的控制结构:

关键要点:

  • 条件语句:if-else 和 switch 语句控制程序分支
  • 循环语句:for、while、do-while 和 foreach 控制重复执行
  • 跳转语句:break、continue、return 控制程序流程
  • 模式匹配:现代 C# 提供更强大的条件判断能力

最佳实践:

  • 优先使用 foreach 遍历集合
  • 合理使用 switch 表达式简化代码
  • 避免深层嵌套,提高代码可读性
  • 注意循环性能,避免不必要的重复计算
  • 适当使用 break 和 continue 优化循环逻辑

下一步: 在下一章中,我们将学习方法和函数,了解如何将代码组织成可重用的模块。

延伸阅读

本站内容仅供学习和研究使用。