开发者

Casting to Collection<interface>

开发者 https://www.devze.com 2023-04-08 12:49 出处:网络
With this: public class Widget : IWidget {} Why does collection2 == null here: var collection1 = collectionView.Sour开发者_如何学JAVAceCollection as ObservableCollection<Widget>;

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

精彩评论

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