开发者

Casting to Collection<interface>

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜