c#从抽象类的静态方法获取继承的类类型

时间:2018-09-17 09:11:01

标签: c# inheritance static

我正在寻找从基类中定义的此类的静态方法中获取继承类的类型的方法。我希望代码片段可以使它更加清晰。

这是我尝试过的方法,但这反映了基本类型,而不是子类型:

abstract class Parent()
{    
    static Parent MyMethod()
    {   
        // I get the parent type but I want the child type         
        Type thisObjType = MehtodBase.GetCurrentMethod().DeclaringType;

        // Fails because I try to instantiate an abstract object
        Parent myChildObj = (Parent)Activator.CreateInstance(thisObjType);
        // ...

        return myChildObj;
    }
}


class Child : Parent
{        
}     

对该方法的调用失败,因为传递的类型是父类型而不是子类型。

Child myChild = (Child)Child.MyMethod()

我已经找到了,但这不是我正在寻找的解决方案:Get derived class type from a base's class static method 如果可能的话,我会尽量避免使用泛型。

如何从静态方法中获取对象的类型? 预先谢谢你!

0 个答案:

没有答案
相关问题