使用Type </person> </object>的变量类型将ICollection <object>转换为另一个类型ICollection <person>

时间:2014-05-31 12:14:24

标签: c# .net reflection

我尝试填充ICollection<Person>ICollection<T>的属性类型。我给出了对象列表类型List<object>ICollection<object>无论如何我不能设置ICollection<Person>的值属性类型1}}按对象列表

if (property.PropertyType.IsGenericType &&
     property.PropertyType.GetGenericTypeDefinition()
       == typeof(ICollection<>))
   {

      Type itemType = property.PropertyType.GetGenericArguments()[0];
      ICollection<object> objectList =GetObjectList();
      property.SetValue(item, objectList);


   }

感谢。

2 个答案:

答案 0 :(得分:1)

您无法将ICollection<Person>设置为ICollection<object>,因为ICollection不是逆变的(通用参数声明中没有in个关键字)。

您将明确地将object的集合转换为Person

if (property.PropertyType.IsGenericType &&
 property.PropertyType.GetGenericTypeDefinition()
   == typeof(ICollection<>))
{
  Type itemType = property.PropertyType.GetGenericArguments()[0];
  ICollection<Person> objectList =GetObjectList().Cast<ICollection<Person>>();
  property.SetValue(item, objectList);
}

答案 1 :(得分:0)

您的解决方案是LINQ,使用方法OfTypeCast来强制转换或选择指定类型的对象。由于您可能无法直接将ICollection<object>转换为ICollection<Person>,但您有一种解决方法可以实现相同目标。

ICollection<Person> objectList = GetObjectList().OfType<Person>().ToList();

ICollection<Person> objectList = GetObjectList().Cast<Person>().ToList();

这段代码会返回List<Person>,因为List<T>实现了ICollection<T>,这意味着ICollection<Person>,所以结果可以分配给您的属性

在大多数情况下,Cast()的执行速度比OfType()快,因为OfType中还涉及类型检查。阅读本文以获取更多信息When to use Cast() and Oftype() in Linq

<强>更新

  object objectList = GetObjectList();
  property.SetValue(item, Convert.ChangeType(objectList, property.PropertyType));

如果类型兼容,这将转换值。此示例不要求您了解基础类型。详细了解ChangeType http://msdn.microsoft.com/en-us/library/dtb69x08.aspx