简体   繁体   中英

Does GetType() and typeof() constitute reflection?

In C# reflection invariably starts with:

myInstance.GetType();

Or:

typeof(MyType);

To get the Type , then when one queries the info about the type eg getting properties, fields, attributes etc. they are certainly performing reflection.

However are the above calls reflection themselves?

I suppose in a academic sense the answer is yes - because you are reflecting on the type. So my second part to the question is: is it evaluated at run time and does it perform a heap allocation the first time? (I know subsequent calls to GetType() on the same type return the same Type instance so .NET must cache the result - but did it have to construct a new Type the first time it was called? Or this something performed at compile time?

The object returned by myInstance.GetType() or typeof(MyType) is an object on the managed heap. So at some point at runtime the allocation must be made. The compiler obviously cannot do a managed heap allocation. (This is in contrast to C/C++ 'functions' like sizeof , where a value is substituted in by the compiler, resulting in no runtime overhead at all.)

So from this, you can conclude that the Type objects are either created at the point your assembly is loaded, or created 'on-demand' when you invoke methods like myInstance.GetType() or typeof(MyType) for the first time.

Which of these is it? As far as I know, it's not specified, so it's hard to say. GetType() , for example, is implemented in the runtime itself:

[MethodImpl(MethodImplOptions.InternalCall)]
public extern Type GetType();

Either way, at some point there will have to be the ( extremely small ) runtime overhead of allocating the Type object for MyType on the managed heap.

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