How WinRT events are interoperate with .NET

有些话、适合烂在心里 提交于 2019-12-05 04:04:28

When you add or remove a delegate to an WinRT event, like this:

this.Loaded += MainPage_Loaded;

this.Loaded -= MainPage_Loaded;

It looks just like you were working with normal .Net events. But this code actually compiles to something like this (Reflector seems to have some trouble decompiling WinRT code, but I think this is what the code actually does):

WindowsRuntimeMarshal.AddEventHandler<RoutedEventHandler>(
    new Func<RoutedEventHandler, EventRegistrationToken>(this.add_Loaded),
    new Action<EventRegistrationToken>(remove_Loaded),
    new RoutedEventHandler(this.MainPage_Loaded));

WindowsRuntimeMarshal.RemoveEventHandler<RoutedEventHandler>(
    new Action<EventRegistrationToken>(this.remove_Loaded),
    new RoutedEventHandler(this.MainPage_Loaded));

This code won't actually compile, because you can't access the add_ and remove_ methods from C#. But you can that in IL, and that's exactly what the compiler does.

It looks like WindosRuntimeMarshal keeps all those EventRegistrationTokens and uses them to unsubscribe when necessary.

Would you accept "there are some amazingly clever people working on the C# language projection" as an answer?

More seriously, what you've discovered is the low level ABI (binary) implementation of the event pattern, the C# language projection knows this pattern and knows how to expose it as C# events. There are classes inside the CLR that implement this mapping.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!