是否可以将列表转换为不同类型的 IList?
Is it Possible to Cast a List to an IList of a Different Type?
以下源绑定到网格的项目源 属性,不知道为什么不能进行此转换;我收到以下错误:"Unable to cast object of type List to IList." 哪里出了问题,在这种情况下有什么解决方法?
public IList<TypeTwo> Source { get; set; }
public SomeViewModel()
{
List<TypeOne> result = db.GetInfo().ToList();
Source = (IList<TypeTwo>)result;
// This works if the IList is of Type TypeOne
// Source = db.GetInfo().ToList();
}
public class TypeTwo {
// The same properties of TypeOne
}
您必须分别转换每个元素,而不是一次转换整个列表:
Source = result
.Select(x => new TypeTwo()
{
SharedProperty1 = x.SharedProperty1,
SharedProperty2 = x.SharedProperty2,
....
})
.ToList();
// only if TypeTwo derives from TypeOne, or implements an explicit cast operator
//Source = result.Cast<TypeTwo>().ToList();
以下源绑定到网格的项目源 属性,不知道为什么不能进行此转换;我收到以下错误:"Unable to cast object of type List to IList." 哪里出了问题,在这种情况下有什么解决方法?
public IList<TypeTwo> Source { get; set; }
public SomeViewModel()
{
List<TypeOne> result = db.GetInfo().ToList();
Source = (IList<TypeTwo>)result;
// This works if the IList is of Type TypeOne
// Source = db.GetInfo().ToList();
}
public class TypeTwo {
// The same properties of TypeOne
}
您必须分别转换每个元素,而不是一次转换整个列表:
Source = result
.Select(x => new TypeTwo()
{
SharedProperty1 = x.SharedProperty1,
SharedProperty2 = x.SharedProperty2,
....
})
.ToList();
// only if TypeTwo derives from TypeOne, or implements an explicit cast operator
//Source = result.Cast<TypeTwo>().ToList();