位置: 文档库 > C#(.NET) > 文档下载预览

《c语言10个经典小程序.doc》

1. 下载的文档为doc格式,下载后可用word或者wps进行编辑;

2. 将本文以doc文档格式下载到电脑,方便收藏和打印;

3. 下载后的文档,内容与下面显示的完全一致,下载之前请确认下面内容是否您想要的,是否完整.

点击下载文档

c语言10个经典小程序.doc

### C#(.NET) 10个经典小程序解析

在.NET开发领域,C#作为核心语言凭借其简洁语法和强大功能成为开发者首选。本文精选10个经典小程序案例,涵盖基础语法、算法实现、系统交互等核心场景,通过代码解析和运行效果展示,帮助开发者快速掌握C#编程精髓。

1. 数字猜谜游戏

通过随机数生成和用户输入交互实现经典猜数字游戏,演示循环控制、条件判断和输入验证。

using System;

class NumberGuessGame
{
    static void Main()
    {
        Random rand = new Random();
        int target = rand.Next(1, 101);
        int attempts = 0;

        Console.WriteLine("猜数字游戏(1-100)");
        
        while (true)
        {
            Console.Write("请输入你的猜测:");
            string input = Console.ReadLine();
            
            if (!int.TryParse(input, out int guess))
            {
                Console.WriteLine("请输入有效数字!");
                continue;
            }

            attempts++;
            
            if (guess  target) Console.WriteLine("太大了!");
            else
            {
                Console.WriteLine($"恭喜!你用了{attempts}次猜中答案。");
                break;
            }
        }
    }
}

运行效果:程序生成1-100随机数,用户通过控制台输入猜测,系统给出大小提示直至猜中。

2. 斐波那契数列生成器

实现递归和非递归两种方式计算斐波那契数列,对比算法效率差异。

using System;

class FibonacciCalculator
{
    // 递归实现(效率低)
    static int FibRecursive(int n)
    {
        return n 

关键点:递归实现简洁但存在重复计算,迭代版本效率更高,适合计算大数。

3. 简单计算器

实现加、减、乘、除四则运算,处理除零异常和非法输入。

using System;

class SimpleCalculator
{
    static void Main()
    {
        Console.WriteLine("简单计算器");
        Console.Write("输入第一个数字:");
        if (!double.TryParse(Console.ReadLine(), out double num1))
        {
            Console.WriteLine("无效输入!");
            return;
        }

        Console.Write("输入运算符(+,-,*,/):");
        char op = Console.ReadKey().KeyChar;
        Console.WriteLine();

        Console.Write("输入第二个数字:");
        if (!double.TryParse(Console.ReadLine(), out double num2))
        {
            Console.WriteLine("无效输入!");
            return;
        }

        try
        {
            double result = op switch
            {
                '+' => num1 + num2,
                '-' => num1 - num2,
                '*' => num1 * num2,
                '/' when num2 != 0 => num1 / num2,
                _ => throw new Exception("不支持的运算符")
            };

            if (op == '/' && num2 == 0)
                throw new DivideByZeroException();

            Console.WriteLine($"结果:{num1} {op} {num2} = {result}");
        }
        catch (DivideByZeroException)
        {
            Console.WriteLine("错误:除数不能为零!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"错误:{ex.Message}");
        }
    }
}

异常处理:使用try-catch捕获除零错误,switch表达式简化运算逻辑。

4. 文件读写操作

演示如何创建、写入和读取文本文件,处理文件访问异常。

using System;
using System.IO;

class FileOperations
{
    static void Main()
    {
        string filePath = "test.txt";
        
        // 写入文件
        try
        {
            string content = "这是C#文件操作示例\n第二行内容";
            File.WriteAllText(filePath, content);
            Console.WriteLine("文件写入成功");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"写入错误:{ex.Message}");
            return;
        }

        // 读取文件
        try
        {
            string readContent = File.ReadAllText(filePath);
            Console.WriteLine("\n文件内容:");
            Console.WriteLine(readContent);
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("错误:文件不存在!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"读取错误:{ex.Message}");
        }
    }
}

关键方法:File.WriteAllText()和File.ReadAllText()简化文件操作流程。

5. 多线程计时器

使用System.Threading实现简单计时器,演示线程基础操作。

using System;
using System.Threading;

class MultiThreadTimer
{
    static void Countdown(int seconds)
    {
        for (int i = seconds; i >= 0; i--)
        {
            Console.WriteLine($"剩余时间:{i}秒");
            Thread.Sleep(1000); // 暂停1秒
        }
        Console.WriteLine("时间到!");
    }

    static void Main()
    {
        Console.WriteLine("多线程计时器启动");
        
        // 创建新线程
        Thread timerThread = new Thread(() => Countdown(5));
        timerThread.Start();

        // 主线程继续执行
        Console.WriteLine("主线程继续运行...");
        Thread.Sleep(2000);
        Console.WriteLine("主线程等待2秒后结束");
    }
}

线程控制:Thread.Sleep()实现精确计时,新线程独立执行倒计时逻辑。

6. 冒泡排序算法

实现经典冒泡排序,演示数组操作和算法优化。

using System;

class BubbleSortDemo
{
    static void BubbleSort(int[] arr)
    {
        int n = arr.Length;
        for (int i = 0; i  arr[j+1])
                {
                    // 交换元素
                    (arr[j], arr[j+1]) = (arr[j+1], arr[j]);
                    swapped = true;
                }
            }
            
            // 优化:本轮无交换则提前结束
            if (!swapped) break;
        }
    }

    static void Main()
    {
        int[] numbers = { 64, 34, 25, 12, 22, 11, 90 };
        
        Console.WriteLine("排序前:");
        Console.WriteLine(string.Join(", ", numbers));

        BubbleSort(numbers);

        Console.WriteLine("\n排序后:");
        Console.WriteLine(string.Join(", ", numbers));
    }
}

算法优化:通过swapped标志减少不必要的循环次数。

7. 简易学生管理系统

使用List集合实现学生信息增删改查功能。

using System;
using System.Collections.Generic;

class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public double Score { get; set; }
}

class StudentManagement
{
    static List students = new List();

    static void AddStudent()
    {
        Console.Write("输入学号:");
        int id = int.Parse(Console.ReadLine());
        
        Console.Write("输入姓名:");
        string name = Console.ReadLine();
        
        Console.Write("输入成绩:");
        double score = double.Parse(Console.ReadLine());

        students.Add(new Student { Id = id, Name = name, Score = score });
        Console.WriteLine("添加成功!");
    }

    static void DisplayAll()
    {
        Console.WriteLine("\n学生列表:");
        foreach (var s in students)
        {
            Console.WriteLine($"学号:{s.Id}, 姓名:{s.Name}, 成绩:{s.Score}");
        }
    }

    static void Main()
    {
        while (true)
        {
            Console.WriteLine("\n1.添加学生 2.显示所有 3.退出");
            char choice = Console.ReadKey().KeyChar;
            Console.WriteLine();

            switch (choice)
            {
                case '1': AddStudent(); break;
                case '2': DisplayAll(); break;
                case '3': return;
                default: Console.WriteLine("无效选择!"); break;
            }
        }
    }
}

集合应用:List提供动态数组功能,简化数据管理。

8. 异步文件下载器

使用async/await实现非阻塞文件下载,演示异步编程模型。

using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;

class AsyncFileDownloader
{
    static async Task DownloadFileAsync(string url, string savePath)
    {
        try
        {
            using (WebClient client = new WebClient())
            {
                Console.WriteLine("开始下载...");
                byte[] data = await client.DownloadDataTaskAsync(url);
                await File.WriteAllBytesAsync(savePath, data);
                Console.WriteLine($"文件已保存到:{savePath}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"下载错误:{ex.Message}");
        }
    }

    static void Main()
    {
        string url = "https://example.com/sample.txt";
        string savePath = "downloaded.txt";
        
        // 启动异步下载
        DownloadFileAsync(url, savePath).Wait();
        
        Console.WriteLine("主线程继续执行...");
    }
}

异步优势:避免UI冻结,提高资源利用率。

9. LINQ查询示例

演示LINQ to Objects的基本查询操作,包括筛选、排序和聚合。

using System;
using System.Linq;

class LINQDemo
{
    static void Main()
    {
        int[] numbers = { 5, 2, 8, 1, 9, 3, 7 };

        // 筛选偶数
        var evenNumbers = numbers.Where(n => n % 2 == 0);
        Console.WriteLine("偶数:");
        foreach (var n in evenNumbers) Console.Write(n + " ");

        // 排序并取前3
        var top3 = numbers.OrderByDescending(n => n).Take(3);
        Console.WriteLine("\n最大的3个数:");
        foreach (var n in top3) Console.Write(n + " ");

        // 计算平均值
        double avg = numbers.Average();
        Console.WriteLine($"\n平均值:{avg:F2}");
    }
}

LINQ特点:声明式编程风格,代码简洁易读。

10. 依赖注入示例

使用.NET Core内置DI容器实现服务注册和解析。

using System;
using Microsoft.Extensions.DependencyInjection;

// 定义服务接口
public interface IMessageService
{
    void Send(string message);
}

// 实现服务
public class EmailService : IMessageService
{
    public void Send(string message)
    {
        Console.WriteLine($"发送邮件:{message}");
    }
}

public class SmsService : IMessageService
{
    public void Send(string message)
    {
        Console.WriteLine($"发送短信:{message}");
    }
}

class DependencyInjectionDemo
{
    static void Main()
    {
        // 创建服务容器
        var serviceCollection = new ServiceCollection();
        serviceCollection.AddTransient();
        // 切换为SmsService只需修改这一行
        // serviceCollection.AddTransient();
        
        var serviceProvider = serviceCollection.BuildServiceProvider();

        // 解析服务
        var messageService = serviceProvider.GetService();
        messageService.Send("Hello DI!");
    }
}

DI优势:降低组件耦合度,便于测试和维护。

### 关键词

C#编程、.NET框架、控制台应用、算法实现、文件操作、多线程编程、集合应用、异步编程、LINQ查询、依赖注入

### 简介

本文精选10个C#(.NET)经典小程序,涵盖基础语法、算法设计、系统交互、异步编程等核心场景。每个案例均包含完整代码实现和运行效果说明,适合.NET开发者快速掌握关键编程技术。通过实际项目演练,帮助读者理解C#语言特性及.NET平台功能。

《c语言10个经典小程序.doc》
将本文以doc文档格式下载到电脑,方便收藏和打印
推荐度:
点击下载文档