C#泛型委托讲解

1. 泛型(Generics)

泛型允许编写类型安全且可重用的代码,避免装箱拆箱操作,提高性能。

泛型类

// 定义泛型类
public class GenericList<T>
{private T[] items;private int count;public GenericList(int capacity){items = new T[capacity];}public void Add(T item){if (count < items.Length)items[count++] = item;}public T Get(int index){if (index >= 0 && index < count)return items[index];throw new IndexOutOfRangeException();}
}// 使用
var intList = new GenericList<int>(10);
var stringList = new GenericList<string>(10);

泛型方法

public class Utility
{// 泛型方法public static void Swap<T>(ref T a, ref T b){T temp = a;a = b;b = temp;}// 带约束的泛型方法public static T Max<T>(T a, T b) where T : IComparable<T>{return a.CompareTo(b) > 0 ? a : b;}
}

泛型约束

// 多种约束类型
public class Repository<T> where T : class, IEntity, new()
{public T Create(){return new T();}
}// 接口约束
public interface IEntity
{int Id { get; set; }
}// 使用示例
public class Product : IEntity
{public int Id { get; set; }public string Name { get; set; }
}

2. 委托(Delegates)

委托是类型安全的函数指针,可以引用静态或实例方法。

基本委托

// 声明委托类型
public delegate void MyDelegate(string message);
public delegate int Calculator(int a, int b);public class DelegateExample
{// 匹配委托签名的方法public static void Method1(string msg){Console.WriteLine($"Method1: {msg}");}public void Method2(string msg){Console.WriteLine($"Method2: {msg}");}public static void Demo(){MyDelegate del = Method1;del += new DelegateExample().Method2;// 多播委托del("Hello");  // 调用所有方法// 委托作为参数ProcessData("Test", Method1);}static void ProcessData(string data, MyDelegate processor){processor(data);}
}

内置委托类型

public class BuiltInDelegates
{public static void Demo(){// Action:无返回值Action<string> print = Console.WriteLine;Action<int, int> printSum = (a, b) => Console.WriteLine(a + b);// Func:有返回值Func<int, int, int> add = (a, b) => a + b;Func<string, bool> isNullOrEmpty = string.IsNullOrEmpty;// Predicate:返回boolPredicate<int> isEven = x => x % 2 == 0;// 使用示例List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };var evenNumbers = numbers.FindAll(isEven);}
}

3. 事件(Events)

事件是特殊的多播委托,提供了发布-订阅模式。

标准事件模式

// 事件参数类
public class StockPriceChangedEventArgs : EventArgs
{public string Symbol { get; set; }public decimal OldPrice { get; set; }public decimal NewPrice { get; set; }
}// 发布者
public class Stock
{private string symbol;private decimal price;// 声明事件public event EventHandler<StockPriceChangedEventArgs> PriceChanged;public Stock(string symbol, decimal price){this.symbol = symbol;this.price = price;}public decimal Price{get { return price; }set{if (price != value){decimal oldPrice = price;price = value;OnPriceChanged(oldPrice, value);}}}// 触发事件的方法protected virtual void OnPriceChanged(decimal oldPrice, decimal newPrice){PriceChanged?.Invoke(this, new StockPriceChangedEventArgs{Symbol = symbol,OldPrice = oldPrice,NewPrice = newPrice});}
}// 订阅者
public class StockMonitor
{public void Subscribe(Stock stock){stock.PriceChanged += Stock_PriceChanged;}private void Stock_PriceChanged(object sender, StockPriceChangedEventArgs e){Console.WriteLine($"Stock {e.Symbol}: {e.OldPrice} -> {e.NewPrice}");}
}

4. 类之间的通信

接口通信

public interface IMessageService
{void SendMessage(string message);
}public class EmailService : IMessageService
{public void SendMessage(string message){Console.WriteLine($"Email: {message}");}
}public class NotificationManager
{private IMessageService messageService;public NotificationManager(IMessageService service){messageService = service;}public void Notify(string message){messageService.SendMessage(message);}
}

事件总线模式

public class EventBus
{private static EventBus instance;private Dictionary<Type, List<Delegate>> subscribers = new Dictionary<Type, List<Delegate>>();public static EventBus Instance{get { return instance ?? (instance = new EventBus()); }}public void Subscribe<T>(Action<T> handler){var type = typeof(T);if (!subscribers.ContainsKey(type))subscribers[type] = new List<Delegate>();subscribers[type].Add(handler);}public void Publish<T>(T eventData){var type = typeof(T);if (subscribers.ContainsKey(type)){foreach (var handler in subscribers[type]){((Action<T>)handler)(eventData);}}}
}// 使用示例
public class OrderCreatedEvent
{public int OrderId { get; set; }public decimal Amount { get; set; }
}// 发布
EventBus.Instance.Publish(new OrderCreatedEvent { OrderId = 1, Amount = 100 });

5. UI线程和后台线程通信

Windows Forms中的线程通信

public partial class MainForm : Form
{// 使用Control.Invokeprivate void BackgroundWork(){Thread.Sleep(2000); // 模拟耗时操作// 更新UI必须在UI线程this.Invoke(new Action(() =>{label1.Text = "工作完成";progressBar1.Value = 100;}));}// 使用BackgroundWorkerprivate void InitializeBackgroundWorker(){BackgroundWorker worker = new BackgroundWorker();worker.WorkerReportsProgress = true;worker.WorkerSupportsCancellation = true;worker.DoWork += (sender, e) =>{for (int i = 0; i <= 100; i++){if (worker.CancellationPending){e.Cancel = true;return;}Thread.Sleep(50);worker.ReportProgress(i);}};worker.ProgressChanged += (sender, e) =>{progressBar1.Value = e.ProgressPercentage;label1.Text = $"进度: {e.ProgressPercentage}%";};worker.RunWorkerCompleted += (sender, e) =>{if (e.Cancelled)label1.Text = "已取消";elselabel1.Text = "完成";};worker.RunWorkerAsync();}
}

WPF中的Dispatcher

public partial class MainWindow : Window
{private void BackgroundOperation(){Task.Run(() =>{// 后台操作string result = PerformCalculation();// 更新UIDispatcher.Invoke(() =>{ResultTextBlock.Text = result;});// 或使用BeginInvoke(异步)Dispatcher.BeginInvoke(new Action(() =>{StatusLabel.Content = "计算完成";}));});}
}

6. 多线程

Thread类

public class ThreadingExample
{private static object lockObject = new object();private static int counter = 0;public static void BasicThreading(){Thread t1 = new Thread(WorkerMethod);Thread t2 = new Thread(() => Console.WriteLine("Lambda线程"));t1.Name = "Worker Thread";t1.IsBackground = true;t1.Start("参数");t2.Start();// 等待线程完成t1.Join();t2.Join();}static void WorkerMethod(object data){Console.WriteLine($"线程 {Thread.CurrentThread.Name}: {data}");// 线程同步lock (lockObject){counter++;Console.WriteLine($"Counter: {counter}");}}
}

ThreadPool

public class ThreadPoolExample
{public static void Demo(){// 使用线程池ThreadPool.QueueUserWorkItem(WorkItem, "任务1");ThreadPool.QueueUserWorkItem(WorkItem, "任务2");// 设置线程池大小ThreadPool.SetMinThreads(4, 4);ThreadPool.SetMaxThreads(10, 10);// 使用ManualResetEvent进行同步ManualResetEvent mre = new ManualResetEvent(false);ThreadPool.QueueUserWorkItem((state) =>{Console.WriteLine("等待信号...");mre.WaitOne();Console.WriteLine("收到信号,继续执行");});Thread.Sleep(2000);mre.Set(); // 发送信号}static void WorkItem(object state){Console.WriteLine($"线程池线程: {state}");}
}

Task并行库 (TPL)

public class TaskExample
{public static async void TaskDemo(){// 创建和启动任务Task<int> task1 = Task.Run(() =>{Thread.Sleep(1000);return 42;});// 继续任务Task task2 = task1.ContinueWith(t =>{Console.WriteLine($"结果: {t.Result}");});// 并行执行多个任务Task[] tasks = new Task[3];for (int i = 0; i < 3; i++){int index = i;tasks[i] = Task.Factory.StartNew(() =>{Console.WriteLine($"任务 {index} 在线程 {Thread.CurrentThread.ManagedThreadId}");});}Task.WaitAll(tasks);// 使用async/awaitint result = await CalculateAsync();Console.WriteLine($"异步结果: {result}");}static async Task<int> CalculateAsync(){await Task.Delay(1000);return 100;}
}

并发集合

public class ConcurrentCollectionExample
{public static void Demo(){// 线程安全的集合ConcurrentDictionary<int, string> dict = new ConcurrentDictionary<int, string>();ConcurrentQueue<string> queue = new ConcurrentQueue<string>();ConcurrentBag<int> bag = new ConcurrentBag<int>();BlockingCollection<string> blocking = new BlockingCollection<string>();// 并行添加数据Parallel.For(0, 100, i =>{dict.TryAdd(i, $"Value{i}");queue.Enqueue($"Item{i}");bag.Add(i);});// 生产者-消费者模式Task producer = Task.Run(() =>{for (int i = 0; i < 10; i++){blocking.Add($"Item{i}");Thread.Sleep(100);}blocking.CompleteAdding();});Task consumer = Task.Run(() =>{foreach (var item in blocking.GetConsumingEnumerable()){Console.WriteLine($"消费: {item}");}});Task.WaitAll(producer, consumer);}
}

7. 多进程

Process类

public class ProcessExample
{public static void ProcessDemo(){// 启动新进程Process process = new Process();process.StartInfo.FileName = "notepad.exe";process.StartInfo.Arguments = "test.txt";process.StartInfo.UseShellExecute = false;process.StartInfo.RedirectStandardOutput = true;process.Start();// 等待进程退出process.WaitForExit();int exitCode = process.ExitCode;// 获取所有进程Process[] processes = Process.GetProcesses();foreach (var p in processes){Console.WriteLine($"{p.ProcessName} - {p.Id}");}}// 进程间通信 - 命名管道public static void NamedPipeServer(){using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe")){Console.WriteLine("等待客户端连接...");pipeServer.WaitForConnection();using (StreamReader sr = new StreamReader(pipeServer))using (StreamWriter sw = new StreamWriter(pipeServer)){sw.AutoFlush = true;string message = sr.ReadLine();Console.WriteLine($"收到: {message}");sw.WriteLine("服务器响应");}}}public static void NamedPipeClient(){using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "testpipe")){pipeClient.Connect();using (StreamReader sr = new StreamReader(pipeClient))using (StreamWriter sw = new StreamWriter(pipeClient)){sw.AutoFlush = true;sw.WriteLine("客户端消息");string response = sr.ReadLine();Console.WriteLine($"收到响应: {response}");}}}
}

进程间通信 - 内存映射文件

public class MemoryMappedFileExample
{public static void CreateMemoryMappedFile(){using (var mmf = MemoryMappedFile.CreateNew("SharedMemory", 10000)){using (var accessor = mmf.CreateViewAccessor()){accessor.Write(0, 42);accessor.Write(4, 3.14f);Console.WriteLine("数据已写入共享内存,按任意键退出...");Console.ReadKey();}}}public static void ReadMemoryMappedFile(){using (var mmf = MemoryMappedFile.OpenExisting("SharedMemory")){using (var accessor = mmf.CreateViewAccessor()){int intValue = accessor.ReadInt32(0);float floatValue = accessor.ReadSingle(4);Console.WriteLine($"读取的值: {intValue}, {floatValue}");}}}
}

综合示例:生产者-消费者模式

public class ProducerConsumerExample
{private readonly Queue<WorkItem> workQueue = new Queue<WorkItem>();private readonly object queueLock = new object();private readonly AutoResetEvent workAvailable = new AutoResetEvent(false);private readonly CancellationTokenSource cancellation = new CancellationTokenSource();public class WorkItem{public int Id { get; set; }public string Data { get; set; }public DateTime CreatedTime { get; set; }}// 生产者public void Producer(){int itemId = 0;while (!cancellation.Token.IsCancellationRequested){var item = new WorkItem{Id = ++itemId,Data = $"工作项 {itemId}",CreatedTime = DateTime.Now};lock (queueLock){workQueue.Enqueue(item);Console.WriteLine($"生产: {item.Data}");}workAvailable.Set(); // 通知消费者Thread.Sleep(1000); // 模拟生产延迟}}// 消费者public void Consumer(int consumerId){while (!cancellation.Token.IsCancellationRequested){workAvailable.WaitOne(); // 等待工作项WorkItem item = null;lock (queueLock){if (workQueue.Count > 0){item = workQueue.Dequeue();}}if (item != null){// 处理工作项Console.WriteLine($"消费者 {consumerId} 处理: {item.Data}");Thread.Sleep(2000); // 模拟处理时间}}}public void Start(){// 启动生产者Task.Factory.StartNew(Producer, TaskCreationOptions.LongRunning);// 启动多个消费者for (int i = 1; i <= 3; i++){int consumerId = i;Task.Factory.StartNew(() => Consumer(consumerId), TaskCreationOptions.LongRunning);}Console.ReadKey();cancellation.Cancel();}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/pingmian/91632.shtml
繁体地址,请注明出处:http://hk.pswp.cn/pingmian/91632.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【DL学习笔记】DL入门指南

DL入门指南 资料课程 李沐老师 《动手学深度学习》 https://tangshusen.me/Dive-into-DL-PyTorch/李宏毅老师课程 https://speech.ee.ntu.edu.tw/~hylee/ml/2021-spring.php DL入门必掌握知识点 数据处理 &#xff1a; numpy、torch地址处理 &#xff1a; os、pathlib文件处…

在 uni-app 中进行路由跳转前的权限验证(检查用户是否登录)

使用场景&#xff1a; 适用于需要登录才能访问的 uni-app 应用保护需要认证的页面不被未授权用户访问统一处理路由跳转的权限控制 /utils/cookies.js下的部分代码内容&#xff1a; // #ifdef H5 import Cookies from js-cookie // #endif// ums const tokenKey user_center_to…

垃圾收集器ParNewCMS与底层三色标记算法详解

垃圾收集技术详解笔记 1. 分代收集理论 当前虚拟机的垃圾收集采用分代收集算法&#xff0c;根据对象存活周期将内存分为不同代区&#xff0c;以优化回收效率。 核心分区&#xff1a; 新生代&#xff08;Young Generation&#xff09;&#xff1a;对象存活周期短&#xff0c;约9…

全排列(回溯算法)

本文参考代码随想录 给定一个 没有重复 数字的序列&#xff0c;返回其所有可能的全排列。 示例: 输入: [1,2,3] 输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] 思路 排列是有序的&#xff0c;在排列问题中不需要startIndex&#xff1b;但排列问题需要一个…

在线任意长度大整数计算器

具体请前往&#xff1a;在线大整数计算器--支持超大整数的加减乘除,幂运算/模运算,最大公约数&#xff0c;最小公倍数

AT6668B芯片说明书

这颗北斗专用单芯片解决方案AT6668B&#xff0c;采用射频前端与基带处理一体化设计&#xff0c;集成北斗二号/三号双模B1IB1C信号处理器。通过优化星历解码算法实现秒级卫星锁定&#xff0c;配合硬件加速的干扰监测模块&#xff0c;在电磁环境复杂的应用场景中仍可维持10Hz高频…

谷歌Chrome浏览器安装插件

因为google浏览器的应用市场(https://chrome.google.com/webstore/category/extensions)在国内无法访问,所以无法在线安装插件,这里提供开发者模式离线安装插件的方法。 1、下载crx脚本 谷歌浏览器的插件离线文件的扩展名为:crx(Firefox火狐浏览器的插件扩展名为fpi)。…

【制造】erp和mes系统建设方案(word)

第一部分 概述 第二部分 方案介绍 第三部分 系统业务流程 3.1 关键需求概括分析 3.1.1 销售管理方面 3.1.2 采购管理方面 3.1.3 仓库管理方面 3.1.4 财务管理方面 3.1.5 人力资源方面 3.2 关键需求具体分析 3.2.1 财务管理 3.2.1.1会计凭证解决 3.2.1.2钞票流…

Spring AI 系列之二十八 - Spring AI Alibaba-基于Nacos的prompt模版

之前做个几个大模型的应用&#xff0c;都是使用Python语言&#xff0c;后来有一个项目使用了Java&#xff0c;并使用了Spring AI框架。随着Spring AI不断地完善&#xff0c;最近它发布了1.0正式版&#xff0c;意味着它已经能很好的作为企业级生产环境的使用。对于Java开发者来说…

IMAP电子邮件归档系统Mail-Archiver

简介 什么是 Mail-Archiver &#xff1f; Mail-Archiver 是一个用于从多个 IMAP 账户归档、搜索和导出电子邮件的 web 应用程序。它提供了一种全面的解决方案&#xff0c;帮助用户管理和存储电子邮件。 主要特点 &#x1f4cc;自动归档&#xff1a;自动归档进出邮件&#xff…

李宏毅深度学习教程 第6-7章 自注意力机制 + Transformer

强烈推荐&#xff01;台大李宏毅自注意力机制和Transformer详解&#xff01;_哔哩哔哩_bilibili 目录 1. 词嵌入&问题情形 2. self-attention 自注意力机制 3. 自注意力的变形 3.1 多头注意力&#xff08;multi-head&#xff09; 3.2 位置编码 3.3 截断自注意力&…

大模型幻觉的本质:深度=逻辑层次,宽度=组合限制,深度为n的神经网络最多只能处理n层逻辑推理,宽度为w的网络无法区分超过w+1个复杂对象的组合

大模型幻觉的本质&#xff1a;深度逻辑层次&#xff0c;宽度组合限制&#xff0c;深度为n的神经网络最多只能处理n层逻辑推理&#xff0c;宽度为w的网络无法区分超过w1个复杂对象的组合&#x1f9e9; "深度逻辑层次"具体含义&#x1f522; "宽度组合限制"具…

2419.按位与最大的最长子数组

Problem: 2419. 按位与最大的最长子数组 思路 子数组按位与的结果&#xff0c;不会超过子数组里的最大值&#xff08;因为 a & b ≤ max(a, b)&#xff09;。 进一步推导&#xff0c;整个数组最大按位与的结果就是数组本身的最大值。 因为最大的那个元素自己作为子数组时&a…

智能时代:先管端点,再谈效率

为什么需要统一端点管理&#xff1f;在混合办公常态化、设备类型爆炸式增长的2025年&#xff0c;分散的端点如同散落各地的哨所。传统管理方式让IT团队疲于应对系统更新、漏洞修复、权限分配等重复劳动&#xff0c;不仅消耗60%以上的运维时间&#xff0c;更可能因响应延迟导致安…

Windows字体simsum.ttf的安装与Python路径设置指南

下载工具&#xff1a; https://fontforge.org/en-US/downloads/windows-dl/ 使用工具&#xff1a; 复制到c:\windows\fonts路径下面。 并复制到运行的python程序同一路径下。比如&#xff1a;c:\pythoncode\new\

GitHub下载项目完整配置SSH步骤详解

GitHub下载项目完整配置步骤&#xff08;从零开始&#xff09; 默认下好了git &#xff0c;在文件夹中右键打开git bash &#xff0c; 如果没有请在csdn搜索教程 第一步&#xff1a;检查并清理现有SSH配置 # 进入.ssh目录 cd ~/.ssh# 备份并删除所有现有密钥&#xff08;避免冲…

数据结构(9)栈和队列

1、栈 1.1 概念与结构 栈是一种特殊的线性表&#xff0c;只允许在固定的一端进行插入和删除元素的操作。进行数据插入和删除的一端称为栈顶&#xff0c;另一端称为栈底。栈里面的数据元素遵循后进先出的原则。栈的底层实现一般可以使用数组或者链表来实现&#xff0c;但数组的…

湖北大学暑期实训优秀作品:面向美丽中国的数据化可视平台

开发背景2024年1月11日&#xff0c;《中共中央国务院关于全面推进美丽中国建设的意见》发布&#xff0c;明确了建设美丽中国的总体要求、主要目标和重点任务&#xff0c;为我国生态文明建设提供了顶层设计和行动指南。系统简介当前&#xff0c;中国正以空前的力度推进生态文明建…

Ubuntu系统VScode实现opencv(c++)随机数与随机颜色

在图像处理与计算机图形学中&#xff0c;随机数与随机颜色的生成常用于增强图像的多样性、可视化多个目标区域、模拟自然现象以及生成测试数据等任务。通过随机化元素的颜色、位置或形状&#xff0c;可以使程序在动态展示、调试输出、以及数据增强等方面更加灵活和丰富。例如&a…

机器学习、深度学习与数据挖掘:三大技术领域的深度解析

基本概念与历史沿革数据挖掘起源于20世纪90年代&#xff0c;是数据库技术、统计学和机器学习交叉融合的产物。它经历了从简单查询到复杂知识发现的演变过程&#xff0c;早期阶段主要关注数据存储和检索&#xff0c;随着IBM、微软等公司的推动&#xff0c;逐渐形成了完整的知识发…