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

前端 未结 8 989
走了就别回头了
走了就别回头了 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 where T : IDerived
    {
        public static void Ping()
        {
            //here you have T = the derived type
        }
    }
    public class DerivedClass : BaseClass, IDerived
    {
        //with : BaseClass 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();    
        }
    }
    

提交回复
热议问题