我使用 ILSpy 反编译了一个程序集,其中一个类特别引起了我的注意:
public class CustomTextStream : NetworkStream
{
private EventHandler<CustomEventArgs> someEvent;
public event EventHandler<CustomEventArgs> SomePublicEvent
{
add
{
EventHandler<CustomEventArgs> eventHandler = this.someEvent;
EventHandler<CustomEventArgs> eventHandler2;
do
{
eventHandler2 = eventHandler;
EventHandler<CustomEventArgs> value2 =
(EventHandler<CustomEventArgs>)Delegate.Combine(eventHandler2, value);
eventHandler =
Interlocked.CompareExchange<EventHandler<CustomEventArgs>>(
ref this.someEvent, value2, eventHandler2);
}
while (eventHandler != eventHandler2);
}
remove
{
// similar stuff...
}
}
}
在代码中,似乎私有委托用于触发实际事件:
if (something != null && somethingElse != 0)
{
this.someEvent(this, new CustomEventArgs(someArg));
}
问题:假设没有发生一些“编译/反编译魔术”,有人能猜出这个自定义访问器背后的想法是什么吗?我对IL不太熟悉,顺便说一句...
(旁注:应用程序是多线程的,并且显然利用了网络。)