2009-11-26 75 views
0
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类型传递的对象类型的通用方法,继承如何返回子类对象?

,因为在实际执行我有很多D1,D2的我的设计模式的深层次,等等......

+1

困惑......在图中是D1/D2 a * type *?或者(根据C#示例)a * variable *?那里有什么签名? – 2009-11-26 07:06:10

+1

我认为该图表示一个类的层次结构... – 2009-11-26 07:12:35

+0

我的观点是,它不符合所有**与代码示例... – 2009-11-26 07:35:30

回答

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);