假设我们有这两个类:
public class Derived : Base
{
public Derived(string s)
: base(s)
{ }
}
public class Base
{
protected Base(string s)
{
}
}
那么在Base中如何得到Derived类的类型呢?答案是使用:this.GetType()
就像如下
class Base
{
public Base()
{
Console.WriteLine("Base Constructor. Calling type: {0}", this.GetType().Name);
}
}
原理说明
在基类中调用 this.GetType() 得到的是运行时的实际类型(派生类),而不是声明类型(基类)。
- GetType() 属于 object,任何实例都可调用,返回运行时的 Type。
- 与 typeof(Base) 的区别:后者返回编译期的静态类型,永远指向基类。
- 常用于基类的日志、序列化、工厂方法中需要知道真实子类的场景。