With this:
public class Widget : IWidget {}
Why does collection2 == null
here:
var collection1 = collectionView.Sour开发者_如何学JAVAceCollection as ObservableCollection<Widget>;
var collection2 = collectionView.SourceCollection as ObservableCollection<IWidget>;
Where SourceCollection is ObservableCollection<Widget>
if the collection is declared as ObservableCollection<Widget>
it cannot be cast to ObservableCollection<IWidget>
. I believe this is possible in .NET 4 but not 3.5 or less - CORRECTION - refer Adam's comment below.
For the above to work you must declare the list as ObservableCollection<IWidget>
then both casts will work. You should always use the interface type where possible anyway.
As an aside when you use the 'as' keyword this is called safe casting. It will return null if the cast is not possible. Explicit casting ... ie (ObservableCollection<IWidget>) collectionView.SourceCollection
will throw an exception if the cast is not possible.
精彩评论