我想請求幫助。 我有以下類:獲取實例類的父類
public class POCOConfiguration : EntityTypeConfiguration<POCO>
{
public POCOConfiguration()
{
}
}
...
POCOConfiguration instance = new POCOConfiguration();
如何從例如類型POCO獲得?
感謝
我想請求幫助。 我有以下類:獲取實例類的父類
public class POCOConfiguration : EntityTypeConfiguration<POCO>
{
public POCOConfiguration()
{
}
}
...
POCOConfiguration instance = new POCOConfiguration();
如何從例如類型POCO獲得?
感謝
instance.GetType().BaseType.GetGenericArguments()[0]
看看是:http://msdn.microsoft.com/en-us/library/b8ytshk6.aspx
有,說明如何獲取類型的實例(步驟3,4和5)
如果類有一個paremeterless構造,那麼你可以寫:
public class POCOConfiguration : EntityTypeConfiguration<POCO> where POCO : new()
{
public POCOConfiguration()
{
var poco = new POCO();
}
}
否則你必須使用反射,見Activator類。
檢查這個
POCOConfiguration instance = new POCOConfiguration();
Type t = instance.GetType().BaseType.GetGenericArguments()[0];
//here t is the type of POCO
將工作...
如果我理解你的權利,你想要得到POCO類型。然後聲明一個方法並像下面這樣調用它:
public Type GetTypeOfPoco<T>(EntityTypeConfiguration<T> entityTypeConfiguration)
{
Type t = typeof(T);
return t;
}
稱之爲;
Type t = GetTypeOfPoco(instance);
如果你專門爲POCO類型這樣的測試,那麼它很容易做的'如果(實例EntityTypeConfiguration){}',而不是使用了反射。 –
我有!我並沒有試圖讓你失望,我的評論更多的是讓其他人指出,在這個例子中,使用反射並不是測試特定類型的最佳方式。 –
你好,你是對的。+1對你的評論 – Talha