简体   繁体   English

c# 反射如何成为运行时事件?

[英]How is c# reflection a runtime event?

Every definition says C# reflections is used to determine type of object in runtime.每个定义都说 C# 反射用于在运行时确定对象的类型。 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).这是因为 c# 是一种类型安全语言(一旦是给定类型,就永远是给定类型)。

Suppose you have 3 classes - one an abstract class say Animal and two classes that derive from it, say Cat and Dog .假设您有 3 个类 - 一个是抽象类Animal和两个派生自它的类,例如CatDog 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".请注意,在您对 Animal 进行编程时,动物不会“只是一个对象”。 Being of (compile) type Animal bears great tiding - bool IsAlive property, Breath() method, and more.属于(编译)类型的 Animal 值得一提 - bool IsAlive属性、 Breath()方法等等。 But when you write your code (ie compile time) your "animal" instance won't have a Tail (because not every animal has a tail).但是当您编写代码(即编译时)时,您的“动物”实例不会有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.这是一件非常普遍的事情,这是一件好事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM