Mar*_*olo 19 c# generics reflection inheritance
我想从其基类的静态方法获取派生类的类型.
如何实现这一目标?
谢谢!
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();
Run Code Online (Sandbox Code Playgroud)
Cod*_*ure 35
这可以使用奇怪的重复模板模式轻松完成
class BaseClass<T>
where T : BaseClass<T>
{
static void SomeMethod() {
var t = typeof(T); // gets type of derived class
}
}
class DerivedClass : BaseClass<DerivedClass> {}
Run Code Online (Sandbox Code Playgroud)
调用方法:
DerivedClass.SomeMethod();
Run Code Online (Sandbox Code Playgroud)
此解决方案会增加少量样板开销,因为您必须使用派生类对基类进行模板化.
如果您的继承树有两个以上的级别,那么它也是限制性的.在这种情况下,您必须选择是否通过模板参数或在其子项上强制使用静态方法的调用.
当然,通过模板我的意思是泛型.
Fra*_*gné 14
如果我没有记错的话,发出的代码BaseClass.Ping()
和DerivedClass.Ping()
是一样的,所以让静没有给它任何参数将无法正常工作的方法.尝试将类型作为参数传递或通过泛型类型参数(您可以在其上强制执行继承约束).
class BaseClass {
static void Ping<T>() where T : BaseClass {
Type t = typeof(T);
}
}
Run Code Online (Sandbox Code Playgroud)
你会这样称呼它:
BaseClass.Ping<DerivedClass>();
Run Code Online (Sandbox Code Playgroud)