Get derived class type from a base's class static method

前端 未结 8 982
走了就别回头了
走了就别回头了 2020-12-01 14:44

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 BaseCla         


        
8条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 14:46

    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() where T : BaseClass {
            Type t = typeof(T);
        }
    }
    

    You would call it like this:

    BaseClass.Ping();
    

提交回复
热议问题