我想从其基类的静态方法中获取派生类的类型。
如何实现?
谢谢!
class BaseClass {
static void Ping () {
Type t = this.GetType(); // should be DerivedClass, but it is not possible with a static method
}
}
class DerivedClass : BaseClass {}
// somewhere in the code
DerivedClass.Ping();
最佳答案
这可以使用 curiously recurring template pattern 轻松完成
class BaseClass<T>
where T : BaseClass<T>
{
static void SomeMethod() {
var t = typeof(T); // gets type of derived class
}
}
class DerivedClass : BaseClass<DerivedClass> {}
调用方法:
DerivedClass.SomeMethod();
此解决方案增加了少量样板文件开销,因为您必须使用派生类对基类进行模板化。
如果您的继承树超过两层,这也是有限制的。在这种情况下,您必须选择是传递模板参数还是将当前类型强加给其子项以调用您的静态方法。
当然,我所说的模板是指泛型。
关于c# - 从基类的静态方法获取派生类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3064227/