What is Type Object in Heap

安稳与你 提交于 2019-11-30 15:14:04

The Type object also contains the bytes that back any static fields on the type as well as a method table with one entry per method defined within the type.

Each entry in the method table points to JIT-compiled native code if the method has been executed at least once.

The type object is created the first time the type is instantiated or the first time a static type member is referenced.

I highly recommend buying a copy of Jeffrey Richter's book, CLR via C# if you want to get a really deep understanding of what the CLR does. The section titled "How Things Relate at Runtime" in chapter 4 covers the .NET type allocation process on the heap in detail.

The May 2005 edition of MSDN magazine has an article titled "JIT and Run: Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects" with some good information as well, specifically the sections on Type Fundamentals and MethodTable.

All the cast exceptions, type match and mismatch are done and handled by the CLR with the help of Type Object in .Net. Simplest and fastest way to create a type's Type Object is via typeof operator as shown below:

    var fileTypeObjectInHeap = typeof(File);

If you have ever done something like this in C# - comparing the type of an object o with some known type (here FileInfo):

var fileName = @"C:\sample.txt";
object o = new FileInfo(fileName);
if (o.GetType() == typeof(FileInfo)) { ... }

then you have used Type Object of that type unknowingly.

Corresponding to every type being used by your application (AppDomain to be precise) there is single instance of Type Object in heap which is referred for all such purposes. For more details and internals - quoting Jeffrey Richter from CLR via C# Fourth edition:

a Type object represents a type reference that is a lightweight object. If you want to learn more about the type itself, then you must acquire a TypeInfo object, which represents a type definition. You can convert a Type object to a TypeInfo object by calling System.Reflection.IntrospectionExtensions’ GetTypeInfo extension method.

Type typeReference = ...; // For example: o.GetType() or typeof(Object) 
TypeInfo typeDefinition = typeReference.GetTypeInfo();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!