2012-05-23 63 views
6

我想請求幫助。 我有以下類:獲取實例類的父類

public class POCOConfiguration : EntityTypeConfiguration<POCO> 
{ 
    public POCOConfiguration() 
    { 

    } 
} 

...

POCOConfiguration instance = new POCOConfiguration(); 

如何從例如類型POCO獲得?

感謝

回答

9
instance.GetType().BaseType.GetGenericArguments()[0] 
0

如果類有一個paremeterless構造,那麼你可以寫:

public class POCOConfiguration : EntityTypeConfiguration<POCO> where POCO : new() 
{  
    public POCOConfiguration() 
    { 
     var poco = new POCO(); 
    } 
} 

否則你必須使用反射,見Activator類。

0

檢查這個

POCOConfiguration instance = new POCOConfiguration(); 
Type t = instance.GetType().BaseType.GetGenericArguments()[0]; 
//here t is the type of POCO 

將工作...

+1

如果你專門爲POCO類型這樣的測試,那麼它很容易做的'如果(實例EntityTypeConfiguration ){}',而不是使用了反射。 –

+0

我有!我並沒有試圖讓你失望,我的評論更多的是讓其他人指出,在這個例子中,使用反射並不是測試特定類型的最佳方式。 –

+0

你好,你是對的。+1對你的評論 – Talha

0

如果我理解你的權利,你想要得到POCO類型。然後聲明一個方法並像下面這樣調用它:

public Type GetTypeOfPoco<T>(EntityTypeConfiguration<T> entityTypeConfiguration) 
{ 
    Type t = typeof(T); 
    return t; 
} 

稱之爲;

Type t = GetTypeOfPoco(instance);