C# (Delegate/Event) VS C++ (callback 机制)

特性C# Delegate/EventC++ callback
函数指针支持类型安全,支持多播委托std::function, 函数指针
事件系统内建 event 关键字和封装机制需自己实现观察者模式或 signal-slot
安全性高,外部不能随意触发事件低,自行控制
简洁性高,语法内建支持相对复杂

Delegate委托的定义与使用

using System;
using System.Collections.Generic;
public delegate void Notify(string message); // 定义一个委托类型
class Program
{
    static void Main()
    {
        Notify notifyHandler = ShowMessage;
        notifyHandler("Hello from delegate!");
    }

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

Multicast Delegate(多播委托)

一个委托可以包含多个方法(链式调用)

Notify notify = Method1;
notify += Method2;

notify("Chained Call");

void Method1(string msg) => Console.WriteLine($"[1] {msg}");
void Method2(string msg) => Console.WriteLine($"[2] {msg}");

输出:
[1] Chained Call
[2] Chained Call

事件(Event)

事件是对委托的封装,只能在声明它的类内部触发,外部只能订阅。

using System;
using System.Collections.Generic;
public delegate void Notify(string message); // 定义一个委托类型

public class Alarm
{
    public event Notify OnAlarm; // 声明事件(基于委托)

    public void Trigger(string time)
    {
        OnAlarm?.Invoke($"Alarm triggered at {time}");
    }
}

class Program
{
    static void Main()
    {
        Alarm alarm = new Alarm();
        alarm.OnAlarm += msg => Console.WriteLine(msg);

        alarm.Trigger("07:00 AM");
    }
}

C++ 示例(等价的 callback 机制)

#include <iostream>
#include <functional>

void Notify(const std::string& msg) {
    std::cout << msg << std::endl;
}

int main() {
    std::function<void(std::string)> callback = Notify;
    callback("Hello from std::function!");
}

项目演示:图形系统(Interface+Delegate+Event)

using System;
using System.Collections.Generic;

namespace ShapeEventDemo
{
    // 1. 接口定义
    public interface IShape
    {
        string Name { get; }
        double Area();
    }

    // 2. 圆形类
    public class Circle : IShape
    {
        public double Radius { get; set; }
        public string Name => "Circle";

        public double Area() => Math.PI * Radius * Radius;
    }

    // 3. 正方形类
    public class Square : IShape
    {
        public double Side { get; set; }
        public string Name => "Square";

        public double Area() => Side * Side;
    }

    // 4. 委托定义(事件的签名)
    public delegate void ShapeCreatedHandler(IShape shape);

    // 5. 工厂类:创建图形并触发事件
    public class ShapeFactory
    {
        public event ShapeCreatedHandler OnShapeCreated;

        public IShape CreateCircle(double radius)
        {
            var circle = new Circle { Radius = radius };
            OnShapeCreated?.Invoke(circle); // 触发事件
            return circle;
        }

        public IShape CreateSquare(double side)
        {
            var square = new Square { Side = side };
            OnShapeCreated?.Invoke(square); // 触发事件
            return square;
        }
    }

    // 6. 主程序
    class Program
    {
        static void Main()
        {
            var factory = new ShapeFactory();

            // 订阅事件:控制台输出日志
            factory.OnShapeCreated += shape =>
            {
                Console.WriteLine($"[LOG] Created: {shape.Name}, Area = {shape.Area():F2}");
            };

            // 使用接口创建图形
            IShape s1 = factory.CreateCircle(5);
            IShape s2 = factory.CreateSquare(4);
        }
    }
}

输出:
[LOG] Created: Circle, Area = 78.54
[LOG] Created: Square, Area = 16.00

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值