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
英文地址,請注明出處:http://en.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;逐漸形成了完整的知識發…