I saw very good questions about the stack overflow regarding delegates, events, and the implementation of these two .NET functions. One question, in particular, “ How do C # events work behind the scenes? ”, Gave an excellent answer that explains some subtle points very well.
The answer to the above question does the following:
When you declare a field event ... the compiler generates methods and a private field (of the same type as the delegate). Inside the class, when you refer to the ElementAddedEvent you mean the field. outside the classroom, you mean Field
An MSDN article related to the same issue (" Field Events ") adds:
The concept of raising an event is equivalent to the delegate represented by the event - thus, there is no special construction language for creating events.
Wanting to continue learning, I built a test project to view the IL that the event and delegate were compiled for:
public class TestClass
{
public EventHandler handler;
public event EventHandler FooEvent;
public TestClass()
{ }
}
I expected the delegate field handlerand the event to FooEventbe compiled with approximately the same IL code, and some additional methods to access the field generated by the compiler FooEvent. But the generated IL was not quite what I expected:
.class public auto ansi beforefieldinit TestClass
extends [mscorlib]System.Object
{
.event [mscorlib]System.EventHandler FooEvent
{
.addon instance void TestClass::add_FooEvent(class [mscorlib]System.EventHandler)
.removeon instance void TestClass::remove_FooEvent(class [mscorlib]System.EventHandler)
}
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
// Constructor IL hidden
}
.field private class [mscorlib]System.EventHandler FooEvent
.field public class [mscorlib]System.EventHandler handler
}
- , add remove, , , IL. , .event, .method, .
: , .event IL? IL , .method? .event .method?