Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 创建动态创建的泛型集合的实例_C#_Reflection - Fatal编程技术网

C# 创建动态创建的泛型集合的实例

C# 创建动态创建的泛型集合的实例,c#,reflection,C#,Reflection,当我不知道结果类型时,如何将对象强制转换为泛型集合 ICollection<IEntity> entityCollection = modelPropertyInfo.GetValue(result) as ICollection<IEntity>; if (entityCollection == null) { var targetType = prop.Attribute("target").Value; string entityTypeString =

当我不知道结果类型时,如何将对象强制转换为泛型集合

ICollection<IEntity> entityCollection = modelPropertyInfo.GetValue(result) as ICollection<IEntity>;
if (entityCollection == null)
{
   var targetType = prop.Attribute("target").Value;
   string entityTypeString = "MyNamespace." + targetType + ", MyAssambly";
   Type entityType = GetTypeFromCache(entityTypeString); // here I get right type or null
   if (entityType != null)
   {
       object o = Activator.CreateInstance(typeof(Collection<>).MakeGenericType(new Type[] { entityType })); // how I have instance of genereic collection
       // how to do something like this:
       // entityCollection = o as ICollection<entityType> dynamically ???
   }
}
ICollection entityCollection=modelPropertyInfo.GetValue(结果)作为ICollection;
if(entityCollection==null)
{
var targetType=prop.Attribute(“target”).Value;
string entityTypeString=“MyNamespace.+targetType+”,MyAssambly”;
类型entityType=GetTypeFromCache(entityTypeString);//这里我得到了正确的类型或null
if(entityType!=null)
{
object o=Activator.CreateInstance(typeof(Collection).MakeGenericType(new Type[]{entityType}));//我如何拥有genereic集合的实例
//如何做这样的事情:
//entityCollection=o作为ICollection动态执行???
}
}

在抽象方面,您希望集合是什么:您认为它将始终是哪个接口或基类?它是实现IEntity接口的类,但当我尝试这样做时:我认为
集合
根本无法转换为
ICollection
,因为
ICollection
不是协变的。它是实现IEntity接口的类,是的,我可以创建集合的实例,但设置agregated实体的属性时出现问题,例如,实体具有ICollection类型的属性,我创建了IEntity集合,并将相同的项(狗)添加到此集合(狗实现了IEntity),但当我尝试将ICollection的属性设置为collection类型的属性时,CL运行时引发异常。。。