本文介绍了从基类的静态方法获取派生类类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从其基类的静态方法中获取派生类的类型.
i would like to get the type of the derived class from a static method of its base class.
如何实现?
谢谢!
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();
推荐答案
如果我没记错的话,为 BaseClass.Ping()
和 DerivedClass.Ping() 是相同的,因此使方法静态而不给它任何参数是行不通的.尝试将类型作为参数传递或通过泛型类型参数(您可以对其实施继承约束).
If I'm not mistaken, the code emitted for BaseClass.Ping()
and DerivedClass.Ping()
is the same, so making the method static without giving it any arguments won't work. Try passing the type as an argument or through a generic type parameter (on which you can enforce an inheritance constraint).
class BaseClass {
static void Ping<T>() where T : BaseClass {
Type t = typeof(T);
}
}
你可以这样称呼它:
BaseClass.Ping<DerivedClass>();
这篇关于从基类的静态方法获取派生类类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!