从基本的类静态方法获取派生类类型 [英] Get derived class type from a base's class static method

查看:94
本文介绍了从基本的类静态方法获取派生类类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从它的基类的静态方法获得派生类的类型。

这怎么可能实现呢?

谢谢!

 类的BaseClass {
  静态无效平(){
     类型T = this.GetType(); //应DerivedClass,但它是不可能与一个静态方法
  }
}
类DerivedClass:BaseClass的{}在code //某处
DerivedClass.Ping();


解决方案

如果我没有记错,为 BaseClass.Ping发出()的code DerivedClass.Ping()是一样的,所以使得静态方法没有给它任何参数将无法工作。尝试传递类型作为参数或通过泛型类型参数(您可以强制继承约束)。

 类的BaseClass {
    静态无效平< T>()其中T:BaseClass的{
        类型T = typeof运算(T);
    }
}

您会这样称呼它:

  BaseClass.Ping< D​​erivedClass>();

i would like to get the type of the derived class from a static method of its base class.

How can this be accomplished?

Thanks!

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

解决方案

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);
    }
}

You would call it like this:

BaseClass.Ping<DerivedClass>();

这篇关于从基本的类静态方法获取派生类类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆