简体   繁体   中英

How is c# reflection a runtime event?

Every definition says C# reflections is used to determine type of object in runtime. Can the type of an object change in runtime? Can anybody please provide me an example.

Of course an entity can change its runtime type during runtime. It just can't change its compile type. This is because c# is a type safe language (once a given type, always a given type).

Suppose you have 3 classes - one an abstract class say Animal and two classes that derive from it, say Cat and Dog . Then

Animal animal = new Dog(); //compile time type is Animal runtime type is Dog
Console.WriteLine(animal.GetType().Name); // Dog
...
animal = new Cat(); // compile time type is still Animal (c# is Type safe)
// but runtime type just changed to Cat;
Console.WriteLine(animal.GetType().Name); // Cat

Notice that all the while you are programming your Animal animal will not be "just an object". Being of (compile) type Animal bears great tiding - bool IsAlive property, Breath() method, and more. But when you write your code (ie compile time) your "animal" instance won't have a Tail (because not every animal has a tail). You can only access (with intellisense for example) things that you are sure it has (only Animal things). That's still saying a lot, but not as much as it's concrete subclasses. It's a very general thing, and that's a good thing.

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