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

时间:2013-08-15 11:01:07

标签: c# reflection

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

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 ???
   }
}

0 个答案:

没有答案