0

I have Jetbrains dotpeek installed on my machine which I use to peek into the way .net types are defined. Most of the types generally come under mscorlib.dll, system.dll and a few other dlls. I am trying to find how the delegate and event keywords are defined in the .net BCL, but I am unable to locate it inside any dll. I am also unable to find any online documentation that reveals where it is defined. Can someone tell me where is the delegate and event keyword defined?

4

1 回答 1

1

I think this question shows that you don't understand the relations between C#, .Net, IL and CLR. I would suggest you to read up on that first.

All keywords of the C# language are just that: keywords of the language. They don't have any representation in any DLLs or in CLR (at least not directly). Only the C# compiler cares about C# keywords and they affect what IL does it produce.

If you decompile DLLs, you can see the code for types and since the delegate and event keywords don't represent types (like e.g. int, decimal or string do), you're not going to find them in any DLL.

If you want to know details about IL, have a look at ECMA 335, which is its specification.

If you look there, you'll find that in IL, event is just a collection of two (or more) methods (§II.18) and that's what the C# event keyword compiles to.

So, if you write code like:

public event EventHandler SomeEvent
{
    add { /* some code */ }
    remove { /* more code */ }
}

Then the C# compiler emits two methods and an event that is composed from those methods. If you don't write the code for add and remove yourself (this is the common case and it's called “field-like event”), then the C# compiler generates it for you, along with a backing field (and the code is not that simple).

The delegate keyword behaves in an interesting way. According to the IL specicifcation (§I.8.9.3), a delegate is a special class that derived from System.Delegate and has a method called Invoke. The code for that method is provided by the CLR, so you won't see anything in there if you decompile some delegate type. And that's exactly what the C# keyword delegate does: if you use it, the compiler emits a class that meets the above criteria.

于 2013-09-08T21:40:26.117 回答