在 C# 中,我发现自己偶尔想在同一事件的调度过程中为某个事件注册一个方法。例如,如果我有一个基于同一事件的连续分派转换状态的类,我可能希望第一个状态的处理程序注销自身并注册第二个处理程序。但是,我不希望在下次触发事件之前调度第二个处理程序。
好消息是,微软的 C# 实现看起来就是这样。事件注册语法糖被替换为对 System.Delegate.Combine 的调用,它只是将当前调用列表和新方法连接到一个单独的列表中,并将其分配给事件属性。这给了我我想要的行为。
所以,我的问题是:这是语言标准保证的行为吗?我希望能够在 mono 下的其他平台上运行我的 C# 代码,并且通常希望确保我不会根据其实现对语言标准做出假设。
我在 MSDN 上找不到任何明确的信息。
如果你想要一个我正在谈论的具体例子,这里有一个例子:
delegate void TestDelegate();
static event TestDelegate TestEvent;
static void Main (string[] args) {
TestEvent += TestDelegateInstanceFirst;
TestEvent();
TestEvent();
}
static void TestDelegateInstanceFirst () {
Console.WriteLine("First");
TestEvent += TestDelegateInstanceSecond;
}
static void TestDelegateInstanceSecond () {
Console.WriteLine("Second");
}
至少在 Windows 上,输出是:
First
First
Second