继承如何返回子类对象?

时间:2009-11-26 06:54:10

标签: c# .net design-patterns inheritance

    Base Class B
    |
    |
    ----
    |   |
    |   |
    D1  D2

public static object GetDerivedClass(Type t1, MyProcess p1)
{
     DerivedClass D1 = null;
     DerivedClass D2 = null;

     if (t1 is typeof(Derived)
     {
            Process(D1,p1);
            return D1;
     }
     else if(t1 is typeof(Derived)
     {
            Process(D2,p1);
            return D2;
     }
}

我的问题是返回作为t1 Type传递的对象类型的通用方法,

因为在实际实现中,我的设计模式有很深的层次结构,有很多D1,D2等......

1 个答案:

答案 0 :(得分:2)

您可以将Process方法重写为通用方法,即

T Process<T>(MyProcess p1) where T : new
{

    // do work
    // apparently your Process method must be creating a new instance
    // this is why I put the new constraint on the type parameter
    T t = new T();

    // set properties of t, etc.

    return t;
}

您的GetDerivedClass方法现在是多余的。只需按以下方式调用Process方法: -

var obj = Process<MyDerivedType>(p1);