What is the “” type?

2019-02-22 22:16发布

问题:

I am using Mono.Cecil to read an assembly generated by Regex.CompileToAssembly(). When I iterate through the types, there is one type in the root namespace named <Module>. The type has no base type. What is this type? Is this some Mono.Cecil artifact or something that is actually a real part of .NET assemblies? What role does it play?

回答1:

The <Module> type is a place-holder for declarations that do not fit the CLI model. Normally relevant only in assemblies that are mixed-mode, containing both code written in a managed language as well as an unmanaged one like C or C++. It is empty for pure managed assemblies.

Those languages support free functions and global variables. The CLR does not directly support that, methods and variables must always be a member of a type. So the metadata generator uses a simple trick, it creates a fake type to be the home of such functions and variables. The name of that fake type is <Module>. It always has internal accessibility to hide the members. There is only ever one of those types, its RID is always 1.

The CLR source code calls it the "Global Class".