C# 转换ICollection<;对象>;到另一种类型的ICollection<;人>;使用类型的变量类型
我尝试填充C# 转换ICollection<;对象>;到另一种类型的ICollection<;人>;使用类型的变量类型,c#,.net,reflection,C#,.net,Reflection,我尝试填充ICollection或ICollection的属性类型。我给出了List或ICollection的对象列表类型。无论如何,我无法按对象列表设置ICollection的值属性类型 if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>)) {
ICollection
或ICollection
的属性类型。我给出了List
或ICollection
的对象列表类型。无论如何,我无法按对象列表设置ICollection
的值属性类型
if (property.PropertyType.IsGenericType &&
property.PropertyType.GetGenericTypeDefinition()
== typeof(ICollection<>))
{
Type itemType = property.PropertyType.GetGenericArguments()[0];
ICollection<object> objectList =GetObjectList();
property.SetValue(item, objectList);
}
if(property.PropertyType.IsGenericType&&
property.PropertyType.GetGenericTypeDefinition()
==类型(ICollection))
{
Type itemType=property.PropertyType.GetGenericArguments()[0];
ICollection objectList=GetObjectList();
SetValue(项,对象列表);
}
谢谢。您的解决方案是LINQ,请使用类型的方法
或强制转换
来强制转换或选择指定类型的对象。因为您可能无法将ICollection
直接转换为ICollection
,但您有一个解决方法来实现相同的转换
ICollection<Person> objectList = GetObjectList().OfType<Person>().ToList();
如果类型兼容,这将转换值。本例不要求您知道基础类型。阅读有关ChangeType的更多信息您不能将ICollection
设置为ICollection
,因为ICollection不是逆变的(在泛型参数声明中的
关键字中没有)
您必须明确地将对象的集合强制转换为人
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);
}
if(property.PropertyType.IsGenericType&&
property.PropertyType.GetGenericTypeDefinition()
==类型(ICollection))
{
Type itemType=property.PropertyType.GetGenericArguments()[0];
ICollection objectList=GetObjectList().Cast();
SetValue(项,对象列表);
}
您遇到了什么错误?@DavidG:属性是一个ICollection
,但是您不能使用ICollection
对象发出SetValue
ICollection
不是逆变的。您不能将ICollection
设置为ICollection
此外,上下文是什么?你真的需要这个吗?忘记类型系统通常是设计不好的标志。例如,实际上,ICollection就是匿名类型,但我可以按itemType访问属性类型(不是ICollection)@Amirhossein在强制转换到对象
后无法重新创建匿名类型。您需要返回一个强类型,但我有itemType(Type itemType=property.PropertyType.GetGenericArguments()[0];)应该离开并将对象添加到列表中,那又怎样呢?您拥有itemType
,但仍然构造了一个无效的ICollection
。无法将对象
类型添加到具有派生强类型的集合中,该操作无效。您可以尝试automapper.orgI无法访问强类型(Person)!你也期待着知道它的类型吗?或者您只想设置GetObjectList()的返回值?设置GetObjectList()的返回值是的,谢谢,但我接受了另一个答案(对我来说更好),我设置了投票,以便uI应该实现IConvertible,以便为每个类使用Convert.ChangeType
。例如,是否有一种方法可以自动完成并重写类。
object objectList = GetObjectList();
property.SetValue(item, Convert.ChangeType(objectList, property.PropertyType));
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);
}