c# - 从基类的静态方法获取派生类类型

标签 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();

最佳答案

这可以使用 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/

相关文章:

c# - dotnet core 获取用于依赖注入(inject)的加载程序集列表

c# - 在 Audit.NET 中审核 n 对 m 关系(数据库优先)

c# - 向 IoC 注册通用 UnitOfWork<> 时出错

c# - UWP 和 WPF 数据库入门 : Roadmap needed

用于以通用方式返回序列的 C++ API

java - 将 entrySet 转换为数组

java - 未经检查的 Actor : Is there a way to avoid it in this case?

Java 反射实例检查不同类

c# - 为什么我不能将 Expression Body 转换为 MethodCallExpression

c# - 在 C# 中使用反射和通用属性