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

前端 未结 8 949
走了就别回头了
走了就别回头了 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 15:02

    In short this is what I tried to answer here. It uses one interface to unify all derived classes and let them all call the same static method from the base class without passing a Type.

    public interface IDerived
    {
    }
    public class BaseClass<T> where T : IDerived
    {
        public static void Ping()
        {
            //here you have T = the derived type
        }
    }
    public class DerivedClass : BaseClass<DerivedClass>, IDerived
    {
        //with : BaseClass<DerivedClass> we are defining the T above
    }
    public class ExampleApp
    {
        public void Main()
        {
            //here we can call the BaseClass's static method through DerivedClass
            //and it will know what Type calls it
            DerivedClass.Ping();    
        }
    }
    
    0 讨论(0)
  • 2020-12-01 15:05

    Why not just use the methods that are there already?

    If you have

    class BaseClass {}
    partial class DerivedClass : BaseClass {}
    

    You can look at

    DerivedClass.GetType().BaseType;
    
    0 讨论(0)
提交回复
热议问题