ran*_*med 3 c# generics entity-framework-6
我正在使用反射动态创建实例。
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);
}
Run Code Online (Sandbox Code Playgroud)
而我的例外是:-“因为Type.ContainsGenericParameters为true,所以无法创建CGenericConfigurationClass`1 [T]的实例。”
看起来其中的一种类型typesTR是泛型类型,并且您试图在不指定泛型类型参数的情况下创建该类型的实例。例如,就好像您试图创建一个实例,List<> 但没有在尖括号<>之间提供类型一样。这是不可能的,Activator.CreateInstance()必须给它一个“封闭的通用类型”。
为此,您可以执行以下操作,但是根据您的示例,我认为这不会很有用,因为您需要创建许多配置实例,并且您可能不知道要传入哪种泛型类型。
var t = type.MakeGenericType(typeof(SomeClassToBeUsedAsGenericTypeParameter));
dynamic configurationInstance = Activator.CreateInstance(t);
...
Run Code Online (Sandbox Code Playgroud)
我的猜测是其中typesTR包含的类型比您期望的要多,并且包含一个通用的基类之一。我认为它应该只包括DClass和EClass,但包括基类之一。
| 归档时间: |
|
| 查看次数: |
3797 次 |
| 最近记录: |