2014-11-08 90 views
0

铸造集合 到一个ObservableCollection 时,我可以投一个 Collection<T>ObservableCollection<T>这样的: InvalidCastException的通过反射

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

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

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

A first chance exception of type 'System.InvalidCastException' occurred in mscorlib.ni.dll Additional information: Object must implement IConvertible.

为什么在正常运行时的转换工作,而不是当我使用反射?

编辑 我结束了“解决”通过不使用Collection<T>作为一种类型,而是直接使用我myProperty.PropertyType类型我的问题。

回答

5

I can cast a Collection<T> to an ObservableCollection<T> like this:

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>

所以它以反射为失败的代码相同的原因失败...

+0

该死的这是令人尴尬的。我有一个编译器错误没有演员,并错误地认为它会投的很好。 – 2014-11-08 16:24:11