简体   繁体   中英

Importance of getting resolved at run-time or compile-time for .GetType () and Typeof () in c#

I recently read and article about .GetType () and Typeof () methods in c#. Now, I know that both of them return System. Type. That article also indicated that it's important to know .GetType () gets resolved at run-time while the other one does at compile-time.

I wonder why it should be considered this fact? Having in mind that the return value of both functions is the same, why we need to know 'when' they get resolved?

Thank you

typeof isn't a method - it's an operator . That's how it's resolved at compile time. They don't do the same thing, in that for typeof you need to know the actual type or type parameter 1 you want at compile-time, whereas for GetType you don't. For example:

Stream x = GetStreamFromSomewhere();
Type t1 = typeof(Stream); // Always exactly System.IO.Stream
Type t2 = x.GetType();    // Never System.IO.Stream

t2 can never be System.IO.Stream , because that's an abstract type. It could be System.IO.MemoryStream , System.IO.FileStream , or some kind of stream subclass that didn't even exist when I wrote this code. It's the type of the actual object that the value of x refers to. That will always be a stream of some kind, but we don't know until we ask what the type actually is.


1 If you're using typeof(T) then the actual type isn't know by that piece of code at compile-time, but it's the type argument for any particular call. It's not using the execution-time type of a particular object.

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