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

前端 未结 8 969
走了就别回头了
走了就别回头了 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

    This can be accomplished easily using the curiously recurring template pattern

    class BaseClass
        where T : BaseClass
    {
        static void SomeMethod() {
            var t = typeof(T);  // gets type of derived class
        }
    }
    
    class DerivedClass : BaseClass {}
    

    call the method:

    DerivedClass.SomeMethod();
    

    This solution adds a small amount of boilerplate overhead because you have to template the base class with the derived class.

    It's also restrictive if your inheritance tree has more than two levels. In this case, you will have to choose whether to pass through the template argument or impose the current type on its children with respect to calls to your static method.

    And by templates I, of course, mean generics.

提交回复
热议问题