下面代码是Action泛型 in 逆变的代码
void Main()
{
Demo demo = new Demo();
demo.NotifyEvent+=F1;
demo.NotifyEvent+=F2;
demo.NotifyEvent+=F1;
demo.NotifyEvent+=F2;
demo.NotifyEvent+=F3;
demo.InvokeAction();
void F1(A a)
{
nameof(F1).Dump();
}
void F2(B b)
{
nameof(F2).Dump();
}
void F3(B b)
{
throw new Exception("Error");
nameof(F2).Dump();
}
}
class Demo
{
private List<Action<B>> _action = new();
public event Action<B>? NotifyEvent
{
add
{
_action.Add(value);
}
remove
{
_action.Remove(value);
}
}
public void InvokeAction()
{
foreach(var action in _action)
{
action?.Invoke(null);
}
}
}
class A{}
class B:A{}
MulticastDelegate源代码:https://source.dot.net/#System.Private.CoreLib/src/System/MulticastDelegate.cs,115d292376227fdb
笔记来源:https://www.bilibili.com/video/BV1AT411U7H2