刚学会 C# 中 Delegates 的强大之处

发布: (2026年2月25日 GMT+8 13:45)
4 分钟阅读
原文: Dev.to

Source: Dev.to

Just learned the Power of Delegates in C# 的封面图片

BALIGUAT, JUSTINE JERALD Y.

🧠 什么是委托?

Delegates in C# are 类型安全、面向对象的方法指针
In simple terms, a delegate lets you pass a method as a parameter to another method. Think of it as storing a reference to a function inside a variable — but in a structured and safe way.

🏗 创建和使用委托

在教程的第一部分,我学习了如何:

  1. 创建委托
  2. 定义其签名
  3. 将方法作为参数传递
  4. 调用委托

以下是可视化参考:

委托示例

⚠️ 重要规则:参数匹配

委托的参数类型 必须与 被分配的方法的参数类型相匹配。
如果签名不一致,C# 会在编译时抛出错误——这正是委托类型安全的体现。

public delegate void MyDelegate(string message);

public static void ShowMessage(string text)
{
    Console.WriteLine(text);
}

委托也可以引用实例方法

下面是一个委托引用实例方法的示例。

using System;
using System.IO;

namespace DelegateBasicExample
{
    delegate void LogText(string text, DateTime datetime);

    class Program
    {
        static void Main(string[] args)
        {
            Logger logger = new Logger();
            LogText logTextToConsole = new LogText(logger.LogTextToConsole);

            Console.WriteLine("Enter some text: ");
            string input = Console.ReadLine();
            logTextToConsole(input, DateTime.Now);
        }
    }

    class Logger
    {
        public void LogTextToConsole(string text, DateTime datetime)
        {
            Console.WriteLine($"{datetime} : {text}");
        }

        public void LogTextToFile(string text, DateTime datetime)
        {
            using (StreamWriter sw = new StreamWriter("log.txt", true))
            {
                sw.WriteLine($"{datetime} : {text}");
            }
        }
    }
}

委托实例示例

📣 多播委托

可以使用 + 运算符将多个方法分配给同一个委托实例。这使得一个委托能够按顺序调用多个方法。

using System;
using System.IO;

namespace DelegateBasicExample
{
    delegate void LogText(string text, DateTime datetime);

    class Program
    {
        static void Main(string[] args)
        {
            Logger logger = new Logger();

            LogText logToFile   = new LogText(logger.LogTextToFile);
            LogText logToConsole = new LogText(logger.LogTextToConsole);

            // Combine the two delegates
            LogText multiLog = logToConsole + logToFile;

            Console.WriteLine("Enter some text: ");
            string input = Console.ReadLine();
            multiLog(input, DateTime.Now);
        }
    }

    class Logger
    {
        public void LogTextToConsole(string text, DateTime datetime)
        {
            Console.WriteLine($"{datetime} : {text}");
        }

        public void LogTextToFile(string text, DateTime datetime)
        {
            using (StreamWriter sw = new StreamWriter("log.txt", true))
            {
                sw.WriteLine($"{datetime} : {text}");
            }
        }
    }
}

多播委托示例

📦 将委托作为方法参数传递

委托可以传递给另一个方法,然后该方法可以调用它。

using System;
using System.IO;

namespace DelegateBasicExample
{
    delegate void LogText(string text, DateTime datetime);

    class Program
    {
        static void Main(string[] args)
        {
            Logger logger = new Logger();

            LogText logToFile   = new LogText(logger.LogTextToFile);
            LogText logToConsole = new LogText(logger.LogTextToConsole);

            // 将委托传递给另一个方法
            ProcessLog(logToConsole);
        }

        static void ProcessLog(LogText logAction)
        {
            Console.WriteLine("Enter some text: ");
            string input = Console.ReadLine();
            logAction(input, DateTime.Now);
        }
    }

    class Logger
    {
        public void LogTextToConsole(string text, DateTime datetime)
        {
            Console.WriteLine($"{datetime} : {text}");
        }

        public void LogTextToFile(string text, DateTime datetime)
        {
            using (StreamWriter sw = new StreamWriter("log.txt", true))
            {
                sw.WriteLine($"{datetime} : {text}");
            }
        }
    }
}

今天的委托深度解析就到这里。祝编码愉快!

.LogTextToConsole);

LogText multiLogText = LogTextToConsole + LogTextToFile;

Console.WriteLine("Enter some text: ");
LogWithDelParam(multiLogText, Console.ReadLine());
}

static void LogWithDelParam(LogText logText, string text)
{
    logText(text, DateTime.Now);
}
}

图片说明

0 浏览
Back to Blog

相关文章

阅读更多 »

我们与战争部的协议

与五角大楼达成机密AI部署协议 昨天我们与五角大楼达成协议,部署先进的AI系统于机密…