2017-10-28 271 views
-1

enter image description here無法創建,因爲Type.ContainsGenericParameters是真的

我創建一個實例使用動態反映一個實例。

var typesTR = Assembly.GetAssembly(typeof(BGenericConfigurationClass<>)).GetTypes() 
      .Where(type => 
        !string.IsNullOrEmpty(type.Namespace) && 
        (type.Namespace == "EntitiesConfiguration")) 
      .Where(type => type.BaseType != null 
          && type.BaseType.IsGenericType 
          && 
          (type.BaseType.GetGenericTypeDefinition() == typeof(BGenericConfigurationClass<>) || 
          type.BaseType.GetGenericTypeDefinition() == typeof(CGenericConfigurationClass<>))); 

foreach (var type in typesTR) 
{ 

    dynamic configurationInstance = Activator.CreateInstance(type); 
    modelBuilder.Configurations.Add(configurationInstance); 
} 

enter image description here

和我的異常以下內容: - 「無法創建CGenericConfigurationClass`1 [T]的實例,因爲Type.ContainsGenericParameters是真實的。」

+0

該圖像根本沒有幫助。請刪除它並顯示代碼。另外,請注意,EF有一個內置函數來發現程序集中的「EntityTypeConfiguration」類。 –

+0

提供您的實時電子郵件以獲取確切的代碼。 –

+0

我想使用ef的EntityTypeConfiguration類的多級繼承。給我任何想法或任何解決方案。 –

回答

1

它看起來像typesTR中的一種類型是泛型類型,並且您正試圖創建該類型的實例而不指定泛型類型參數。例如,這就好像您試圖創建List<>的實例,但未提供尖括號<>之間的類型。這是不可能的,Activator.CreateInstance()必須給予一個「封閉泛型類型」。

要做到這一點,你可以做類似下面的事情,但根據你的例子,我不認爲這將是非常有用的,因爲你需要創建大量的配置實例,你可能不知道要通過什麼泛型中。

var t = type.MakeGenericType(typeof(SomeClassToBeUsedAsGenericTypeParameter)); 
dynamic configurationInstance = Activator.CreateInstance(t); 
... 

我的猜測是,typesTR中有更多類型比你期待的,包括基類是通用的一個。我認爲它應該只包括DClass和EClass,但包含一個基類。

+0

先生我想使用EntityTypeConfiguration類的實體框架使用多級繼承。上面的圖片顯示主要場景給我任何想法或任何解決方案 –

相關問題