C#中的委托和事件

作者:微信公众号:【架构师老卢】
8-29 13:24
10

概述:C# 语言中的委托和事件#委托和事件是 C# 中用于实现事件驱动编程模型的基本概念。以下是对每个选项的解释以及实际的真实示例。代表委托是一种类型,它表示对具有特定参数列表和返回类型的方法的引用。 委托用于将方法作为参数传递给其他方法。// Define a delegate public delegate void Notify(string message); public class Process {     // Delegate instance     public Notify ProcessCompleted;     public void StartPr

C# 语言中的委托和事件#

委托和事件是 C# 中用于实现事件驱动编程模型的基本概念。以下是对每个选项的解释以及实际的真实示例。

代表

委托是一种类型,它表示对具有特定参数列表和返回类型的方法的引用。 委托用于将方法作为参数传递给其他方法。

// Define a delegate  
public delegate void Notify(string message);  
  
public class Process  
{  
    // Delegate instance  
    public Notify ProcessCompleted;  
  
    public void StartProcess()  
    {  
        // Simulating some process  
        System.Threading.Thread.Sleep(3000);  
  
        // Once the process is completed, call the delegate  
        OnProcessCompleted("Process Completed Successfully");  
    }  
  
    protected virtual void OnProcessCompleted(string message)  
    {  
        // If there are subscribers, notify them  
        ProcessCompleted?.Invoke(message);  
    }  
}  
  
public class Program  
{  
    public static void Main()  
    {  
        Process process = new Process();  
  
        // Subscribe to the delegate  
        process.ProcessCompleted += Message => Console.WriteLine(Message);  
  
        process.StartProcess();  
    }  
}

事件

事件提供了一种将已发生的事情通知多个订阅者的方法。事件基于委托构建,并且只能由拥有它们的类调用。

定义和示例

// Define a delegate  
public delegate void Notify(string message);  
  
// Define a class that publishes an event  
public class Process  
{  
    // Define an event based on that delegate  
    public event Notify ProcessCompleted;  
  
    public void StartProcess()  
    {  
        // Simulating some process  
        System.Threading.Thread.Sleep(3000);  
  
        // Once the process is completed, raise the event  
        OnProcessCompleted("Process Completed Successfully");  
    }  
  
    protected virtual void OnProcessCompleted(string message)  
    {  
        // Raise the event  
        ProcessCompleted?.Invoke(message);  
    }  
}  
  
public class Program  
{  
    public static void Main()  
    {  
        Process process = new Process();  
  
        // Subscribe to the event  
        process.ProcessCompleted += Message => Console.WriteLine(Message);  
  
        process.StartProcess();  
    }  
}

真实示例

场景:日志记录系统

考虑一个日志记录系统,其中应用程序的不同组件需要将消息记录到各种输出,如控制台、文件或远程服务器。委托和事件可用于实现灵活且可扩展的日志记录系统。

using System;  
using System.IO;  
  
// Define a delegate for logging  
public delegate void LogHandler(string message);  
  
// Logger class that raises an event  
public class Logger  
{  
    public event LogHandler LogEvent;  
  
    public void Log(string message)  
    {  
        OnLogEvent(message);  
    }  
  
    protected virtual void OnLogEvent(string message)  
    {  
        LogEvent?.Invoke(message);  
    }  
}  
  
// Subscriber 1: Logs to console  
public class ConsoleLogger  
{  
    public void Subscribe(Logger logger)  
    {  
        logger.LogEvent += LogToConsole;  
    }  
  
    private void LogToConsole(string message)  
    {  
        Console.WriteLine("ConsoleLogger: " + message);  
    }  
}  
  
// Subscriber 2: Logs to file  
public class FileLogger  
{  
    private readonly string filePath;  
  
    public FileLogger(string path)  
    {  
        filePath = path;  
    }  
  
    public void Subscribe(Logger logger)  
    {  
        logger.LogEvent += LogToFile;  
    }  
  
    private void LogToFile(string message)  
    {  
        File.AppendAllText(filePath, "FileLogger: " + message + Environment.NewLine);  
    }  
}  
  
// Subscriber 3: Logs to a remote server (simulated)  
public class RemoteLogger  
{  
    public void Subscribe(Logger logger)  
    {  
        logger.LogEvent += LogToRemoteServer;  
    }  
  
    private void LogToRemoteServer(string message)  
    {  
        // Simulate logging to a remote server  
        Console.WriteLine("RemoteLogger: Sending log to remote server: " + message);  
    }  
}  
  
public class Program  
{  
    public static void Main()  
    {  
        Logger logger = new Logger();  
  
        // Create loggers  
        ConsoleLogger consoleLogger = new ConsoleLogger();  
        FileLogger fileLogger = new FileLogger("log.txt");  
        RemoteLogger remoteLogger = new RemoteLogger();  
  
        // Subscribe loggers to the logger event  
        consoleLogger.Subscribe(logger);  
        fileLogger.Subscribe(logger);  
        remoteLogger.Subscribe(logger);  
  
        // Log a message  
        logger.Log("This is a test log message.");  
  
        // Output will be sent to console, file, and remote server simulation  
    }  
}

总结

  • 委托:类型安全的函数指针,允许将方法作为参数传递。
  • 事件:基于委托构建,允许类在发生事件时通知其他类。
  • 实际示例:使用事件通知不同日志记录机制(控制台、文件、远程服务器)的日志记录系统。
阅读排行