简体   繁体   中英

How does .NET resolve types?

I am curious how .net resolves types. I know there is a compile-time component because you can't compile a program that has using statements or fully qualified types which aren't in the current assembly or a referenced assembly. I wonder if it's the compiler that throughs an error or if it's visual studio that throws a build error if it can't find a reference in the proj file?

I am also wondering how .net finds the assembly at runtime. I know .net uses a JIT compiler that loads assemblies the first time it runs into a type from that assembly. I am curious about how it goes about looking for the type and the search order. Does the assembly manifest tell the runtime exactly where to look for referenced assemblies (like the ASP.NET web.config file)? Any links to blog posts, books, specs, etc would be much appreciated.

The ultimate source of error messages you get when you use an identifier that isn't recognized is the compiler. You'll get an early warning from IntelliSense, it puts the red squiggles under the identifier name.

The compiler records the assembly, namespace and type name in the metadata of the assembly it generates from your source code. For the assembly, it records the display name (like System), the [AssemblyVersion] it found in the reference assembly and the PublicKeyToken, a value that's relevant for strong-named assemblies.

At runtime, it is the job of the CLR to find the assembly back with just those three assembly properties. The jitter will be the one that asks the CLR to find it when it needs to generate code. There are several obscure details about it, associated with overriding the normal lookup rules, you can find them documented in any good book about .NET or MSDN. This MSDN article goes into the details.

The normal way is that it first looks in the GAC, a depository for assemblies and the place where all .NET framework assemblies are stored. The GAC is special since it can store multiple assemblies with the same name but different versions, a strong DLL Hell counter-measure. If it doesn't find it there, using an exact match with those three properties plus the architecture, it then looks in the directory where the EXE is stored, accepting a match if the display name matches. All is well if all assembly properties match and the type can be found back with the same namespace and type name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM