特性 | C# Delegate/Event | C++ 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