简体   繁体   中英

How does GetType() knows the type of a derived class?

Why this works:

Object o = "my string";
Console.WriteLine(o.GetType());

Output:

System.String

This would make sense if the function call was dispatched to the String class, but it didn't since GetType() is not virtual.

The execution-time type is part of the data of the object itself. It's almost like it's a hidden read-only field in System.Object , and GetType() just returns the value of that field. (It's not quite that simple, but that's a reasonable approximation.)

Note that this information is necessary for the CLR to work out where to dispatch virtual methods - so if you were thinking it would work if GetType were virtual, ask yourself how the CLR would know which implementation to call.

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