![](/img/trans.png)
[英]C# Cannot create an instance because Type.ContainsGenericParameters is true
[英]Cannot create an instance of because Type.ContainsGenericParameters is true
我正在使用反射动态创建一个实例。
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);
}
我的异常如下: - “无法创建CGenericConfigurationClass`1 [T]的实例,因为Type.ContainsGenericParameters为真。”
看起来typesTR
中的一个类型是泛型类型,并且您尝试在不指定泛型类型参数的情况下创建该类型的实例。 例如,这就好像您尝试创建List<>
的实例但没有在尖括号<>之间提供类型。 这是不可能的, Activator.CreateInstance()
必须被赋予“封闭的泛型类型”。
为此,您可以执行以下操作,但基于您的示例,我认为这不会非常有用,因为您需要创建大量配置实例,并且您可能不知道要传递的泛型类型。
var t = type.MakeGenericType(typeof(SomeClassToBeUsedAsGenericTypeParameter));
dynamic configurationInstance = Activator.CreateInstance(t);
...
我的猜测是, typesTR
类型比你预期的要多,并且包含一个通用的基类。 我认为它应该只包括DClass和EClass,但包含一个基类。
在我的情况下,当然是不同的,但也与问题中提出的问题有一些相似之处,我设法通过使用以下代码在EF泛型中实现我的实体映射的一部分
protected override void OnModelCreating(ModelBuilder builder)
{
RegisterMaps(builder);
base.OnModelCreating(builder);
}
private static void RegisterMaps(ModelBuilder builder)
{
var mapLists = Assembly.GetExecutingAssembly().GetTypes()
.Where(type => !string.IsNullOrWhiteSpace(type.Namespace)
&& typeof(IEntityMap).IsAssignableFrom(type)
&& type.IsGenericType == false
&& type.IsClass).ToList();
foreach (var item in mapLists)
{
Activator.CreateInstance(item, BindingFlags.Public |
BindingFlags.Instance, null, new object[] { builder }, null);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.