2009-11-26 78 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);