通过反射将Collection <t>转换为ObservableCollection <t>时出现InvalidCastException </t> </t>

时间:2014-11-08 16:04:30

标签: c# reflection windows-phone-8.1

我可以将Collection<T>投射到这样的ObservableCollection<T>

ObservableCollection<MyObject> col1;
col1 = (ObservableCollection<MyObject>)new Collection<MyObject>();

但是当我尝试通过反射做到这一点时,我得到以下错误:

myProperty.SetValue(
    element, 
    Convert.ChangeType(values, myProperty.PropertyType, null)
    , null);
  

类型&#39; System.InvalidCastException&#39;的第一次偶然异常。   发生在mscorlib.ni.dll中附加信息:对象必须   实施IConvertible。

为什么转换在正常运行时工作,但在使用反射时却不行?

修改 我最终解决了#39;我的问题是不使用Collection<T>作为类型,而是直接使用myProperty.PropertyType作为类型。

1 个答案:

答案 0 :(得分:5)

  

我可以将Collection<T>投射到ObservableCollection<T>之类的   这样:

ObservableCollection<MyObject> col1;
col1 = (ObservableCollection<MyObject>)new Collection<MyObject>();

不,你不能......这段代码也会引发InvalidCastExceptionCollection<T>的实例不是ObservableCollection<T>的实例,并且没有从Collection<T>ObservableCollection<T>的转换。它以另一种方式工作:ObservableCollection<T>Collection<T>,因为ObservableCollection<T>继承自Collection<T>

因为代码失败的相同原因导致反射失败...

相关问题