.Net的潘多拉魔盒开箱即用,你学废了吗?

1. 控制台输入输出(基本IO操作)

using System;

class Program
{
    
    
    static void Main()
    {
    
    
        Console.WriteLine("请输入你的名字:");
        string name = Console.ReadLine();
        Console.WriteLine($"你好, {
      
      name}!");
    }
}

用途: 展示如何使用控制台进行用户输入输出操作。


2. 文件读写操作

using System;
using System.IO;

class Program
{
    
    
    static void Main()
    {
    
    
        string path = @"test.txt";
        // 写入文件
        File.WriteAllText(path, "Hello World!");
        // 读取文件
        string content = File.ReadAllText(path);
        Console.WriteLine(content);
    }
}

用途: 实现文本文件的读写操作。


3. 异步编程示例(Async/Await)

using System;
using System.Threading.Tasks;

class Program
{
    
    
    static async Task Main()
    {
    
    
        Console.WriteLine("任务开始");
        await Task.Delay(2000); // 模拟异步操作
        Console.WriteLine("任务结束");
    }
}

用途: 展示如何使用异步编程处理耗时任务。


4. JSON序列化与反序列化(使用Newtonsoft.Json库)

using Newtonsoft.Json;
using System;

class Person
{
    
    
    public string Name {
    
     get; set; }
    public int Age {
    
     get; set; }
}

class Program
{
    
    
    static void Main()
    {
    
    
        Person person = new Person {
    
     Name = "John", Age = 30 };
        // 序列化
        string json = JsonConvert.SerializeObject(person);
        Console.WriteLine("序列化后的JSON: " + json);

        // 反序列化
        Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json);
        Console.WriteLine($"反序列化后的对象: {
      
      deserializedPerson.Name}, {
      
      deserializedPerson.Age}");
    }
}

用途: 实现对象的JSON序列化和反序列化。


5. 多线程示例(使用Thread类)

using System;
using System.Threading;

class Program
{
    
    
    static void PrintNumbers()
    {
    
    
        for (int i = 1; i <= 5; i++)
        {
    
    
            Console.WriteLine(i);
            Thread.Sleep(500); // 模拟耗时操作
        }
    }

    static void Main()
    {
    
    
        Thread t = new Thread(PrintNumbers);
        t.Start();
        t.Join();
        Console.WriteLine("主线程完成");
    }
}

用途: 展示如何使用Thread类进行多线程编程。


6. 集合操作(List 和 Dictionary 示例)

using System;
using System.Collections.Generic;

class Program
{
    
    
    static void Main()
    {
    
    
        List<string> fruits = new List<string> {
    
     "Apple", "Banana", "Orange" };
        fruits.Add("Grapes");
        foreach (var fruit in fruits)
        {
    
    
            Console.WriteLine(fruit);
        }

        Dictionary<string, int> fruitPrices = new Dictionary<string, int>
        {
    
    
            {
    
     "Apple", 5 },
            {
    
     "Banana", 2 }
        };
        fruitPrices["Orange"] = 3;

        foreach (var item in fruitPrices)
        {
    
    
            Console.WriteLine($"{
      
      item.Key}: ${
      
      item.Value}");
        }
    }
}

用途: 展示如何使用集合(List 和 Dictionary)进行操作。


7. 事件和委托(Delegates and Events)

using System;

class Program
{
    
    
    public delegate void Notify();
    public static event Notify OnProcessCompleted;

    static void Main()
    {
    
    
        OnProcessCompleted += ProcessCompletedHandler;
        Console.WriteLine("任务进行中...");
        OnProcessCompleted?.Invoke();
    }

    static void ProcessCompletedHandler()
    {
    
    
        Console.WriteLine("任务已完成!");
    }
}

用途: 展示如何使用委托和事件处理异步通知。


8. Linq 查询

using System;
using System.Linq;

class Program
{
    
    
    static void Main()
    {
    
    
        int[] numbers = {
    
     1, 2, 3, 4, 5, 6 };
        var evenNumbers = numbers.Where(n => n % 2 == 0);

        Console.WriteLine("偶数:");
        foreach (var num in evenNumbers)
        {
    
    
            Console.WriteLine(num);
        }
    }
}

用途: 使用Linq进行数组或集合的查询和过滤。


9. 属性(Properties)示例

using System;

class Person
{
    
    
    private int age;

    public int Age
    {
    
    
        get {
    
     return age; }
        set
        {
    
    
            if (value >= 0)
                age = value;
            else
                Console.WriteLine("年龄不能为负数");
        }
    }
}

class Program
{
    
    
    static void Main()
    {
    
    
        Person person = new Person();
        person.Age = 30;
        Console.WriteLine($"年龄: {
      
      person.Age}");

        person.Age = -5; // 错误设置
    }
}

用途: 演示如何使用属性封装数据。


10. 接口(Interface)实现

using System;

interface IDrawable
{
    
    
    void Draw();
}

class Circle : IDrawable
{
    
    
    public void Draw()
    {
    
    
        Console.WriteLine("画一个圆形");
    }
}

class Program
{
    
    
    static void Main()
    {
    
    
        IDrawable drawable = new Circle();
        drawable.Draw();
    }
}

用途: 展示如何实现接口并定义多态行为。


11. 数据库操作(使用 ADO.NET 连接SQL Server)

using System;
using System.Data.SqlClient;

class Program
{
    
    
    static void Main()
    {
    
    
        string connectionString = "Data Source=server;Initial Catalog=database;User ID=user;Password=password";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
    
    
            connection.Open();
            string query = "SELECT COUNT(*) FROM Users";
            SqlCommand command = new SqlCommand(query, connection);
            int userCount = (int)command.ExecuteScalar();
            Console.WriteLine($"用户总数: {
      
      userCount}");
        }
    }
}

用途: 展示如何通过 ADO.NET 操作数据库。

扫描二维码关注公众号,回复: 17479641 查看本文章

12. 依赖注入(使用Microsoft.Extensions.DependencyInjection)

using System;
using Microsoft.Extensions.DependencyInjection;

interface IMessageService
{
    
    
    void SendMessage(string message);
}

class EmailService : IMessageService
{
    
    
    public void SendMessage(string message)
    {
    
    
        Console.WriteLine("发送邮件: " + message);
    }
}

class Program
{
    
    
    static void Main()
    {
    
    
        var serviceProvider = new ServiceCollection()
            .AddSingleton<IMessageService, EmailService>()
            .BuildServiceProvider();

        var messageService = serviceProvider.GetService<IMessageService>();
        messageService.SendMessage("Hello, Dependency Injection!");
    }
}

用途: 展示如何在C#中使用依赖注入。


13. WPF 简单窗口应用

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="200" Width="400">
    <Grid>
        <Button Content="Click Me" HorizontalAlignment="Center" VerticalAlignment="Center" Click="Button_Click"/>
    </Grid>
</Window>
using System.Windows;

namespace WpfApp
{
    
    
    public partial class MainWindow : Window
    {
    
    
        public MainWindow()
        {
    
    
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
    
    
            MessageBox.Show("按钮点击了!");
        }
    }
}

用途: 演示如何使用WPF创建简单的GUI程序。


14. 异常处理示例

using System;

class Program
{
    
    
    static void Main()
    {
    
    
        try
        {
    
    
            int number = int.Parse("abc");
        }
        catch (FormatException ex)
        {
    
    
            Console.WriteLine("格式错误: " + ex.Message);
        }
        finally
        {
    
    
            Console.WriteLine("处理完成");
        }
    }
}

用途: 演示如何捕获和处理异常。


15. 动态对象与 ExpandoObject 使用

using System;
using System.Dynamic;

class Program
{
    
    
    static void Main()
    {
    
    
        dynamic person = new ExpandoObject();
        person.Name = "John";
        person.Age = 30;
        person.SayHello = new Action(() => Console.WriteLine($"Hello, my name is {
      
      person.Name}"));

        person.SayHello();
    }
}

用途: 展示如何使用 ExpandoObject 实现动态对象。


16. XML 文件读写

using System;
using System.Xml.Linq;

class Program
{
    
    
    static void Main()
    {
    
    
        string filePath = "person.xml";

        // 创建XML
        XElement person = new XElement("Person",
            new XElement("Name", "John"),
            new XElement("Age", 30)
        );
        person.Save(filePath);

        // 读取XML
        XElement loadedPerson = XElement.Load(filePath);
        Console.WriteLine($"Name: {
      
      loadedPerson.Element("Name").Value}");
        Console.WriteLine($"Age: {
      
      loadedPerson.Element("Age").Value}");
    }
}

用途: 实现XML文件的创建与读取,常用于配置文件操作。


17. 正则表达式匹配

using System;
using System.Text.RegularExpressions;

class Program
{
    
    
    static void Main()
    {
    
    
        string input = "My phone number is 123-456-7890.";
        string pattern = @"\d{3}-\d{3}-\d{4}";
        Match match = Regex.Match(input, pattern);

        if (match.Success)
        {
    
    
            Console.WriteLine($"找到电话号码: {
      
      match.Value}");
        }
    }
}

用途: 使用正则表达式查找特定模式的字符串。


18. 垃圾回收与 IDisposable 接口

using System;

class Resource : IDisposable
{
    
    
    public void Dispose()
    {
    
    
        Console.WriteLine("释放资源");
    }
}

class Program
{
    
    
    static void Main()
    {
    
    
        using (Resource res = new Resource())
        {
    
    
            Console.WriteLine("使用资源");
        }
        // 资源自动释放
    }
}

用途: 展示如何使用 IDisposable 接口进行资源管理与垃圾回收。


19. 委托链与多播委托

using System;

class Program
{
    
    
    public delegate void Notify();

    static void Main()
    {
    
    
        Notify notify = SayHello;
        notify += SayGoodbye;

        notify();
    }

    static void SayHello()
    {
    
    
        Console.WriteLine("Hello!");
    }

    static void SayGoodbye()
    {
    
    
        Console.WriteLine("Goodbye!");
    }
}

用途: 展示如何使用委托链(多播委托)来调用多个方法。


20. 反射(Reflection)

using System;
using System.Reflection;

class Program
{
    
    
    static void Main()
    {
    
    
        Type type = typeof(Person);
        Console.WriteLine("类名: " + type.Name);

        foreach (var prop in type.GetProperties())
        {
    
    
            Console.WriteLine("属性: " + prop.Name);
        }
    }
}

class Person
{
    
    
    public string Name {
    
     get; set; }
    public int Age {
    
     get; set; }
}

用途: 通过反射获取类型信息,动态地分析和操作对象。


21. 委托泛型(使用Func 和 Action)

using System;

class Program
{
    
    
    static void Main()
    {
    
    
        Func<int, int, int> add = (a, b) => a + b;
        int result = add(3, 4);
        Console.WriteLine($"3 + 4 = {
      
      result}");

        Action<string> printMessage = message => Console.WriteLine(message);
        printMessage("Hello from Action!");
    }
}

用途: 展示如何使用泛型委托 FuncAction 实现灵活的回调机制。


22. Task并行库(TPL)并发编程

using System;
using System.Threading.Tasks;

class Program
{
    
    
    static async Task Main()
    {
    
    
        Task task1 = Task.Run(() => DoWork("任务1"));
        Task task2 = Task.Run(() => DoWork("任务2"));

        await Task.WhenAll(task1, task2);
        Console.WriteLine("所有任务完成");
    }

    static void DoWork(string taskName)
    {
    
    
        Console.WriteLine($"{
      
      taskName} 正在执行...");
        Task.Delay(2000).Wait();
        Console.WriteLine($"{
      
      taskName} 完成");
    }
}

用途: 演示如何使用Task并行库处理并发任务。


23. HTTP 客户端(HttpClient 示例)

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    
    
    static async Task Main()
    {
    
    
        using (HttpClient client = new HttpClient())
        {
    
    
            string url = "https://jsonplaceholder.typicode.com/posts/1";
            string response = await client.GetStringAsync(url);
            Console.WriteLine(response);
        }
    }
}

用途: 展示如何通过 HttpClient 发送HTTP请求和处理响应。


24. 构造函数和析构函数

using System;

class Person
{
    
    
    public string Name {
    
     get; private set; }

    public Person(string name)
    {
    
    
        Name = name;
        Console.WriteLine($"{
      
      Name} 构造函数被调用");
    }

    ~Person()
    {
    
    
        Console.WriteLine($"{
      
      Name} 析构函数被调用");
    }
}

class Program
{
    
    
    static void Main()
    {
    
    
        Person person = new Person("John");
    }
}

用途: 演示构造函数和析构函数的基本用法。


25. 枚举(Enum)使用

using System;

class Program
{
    
    
    enum Days {
    
     Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }

    static void Main()
    {
    
    
        Days today = Days.Wednesday;
        Console.WriteLine($"今天是: {
      
      today}");

        int dayValue = (int)today;
        Console.WriteLine($"今天是周几(数值): {
      
      dayValue}");
    }
}

用途: 使用枚举来表示一组相关的常量。


这25个C#实战示例涵盖了广泛的场景,从基础IO操作到高级的异步编程、LINQ查询、反射、网络通信等,每个示例都可以进一步扩展并结合实际应用来增强你的代码深度。希望这些能对你有帮助!

猜你喜欢

转载自blog.csdn.net/Hellc007/article/details/142983680