Interface inheritance and inheritance

Each element has an interface IItem. In addition, there is an interface known as IDrawableItemthat which inherits from Item.

The code below attempts to draw an element that can be pulled out but cannot, since the collection of this class only saves IItem. You can add everything that inherits from IItemto this class, but using other methods can only be achieved by casting.

foreach (var item in Items) {
    item.Draw();               // The casting would go here.
}

I know how to distinguish, asetc ... but is that acceptable? Is this the best practice?

Just wondering if there are other ways to handle such scenarios.

+5
source share
2

Enumerable.OfType, Items, IDrawableItem:

foreach(var item in Items.OfType<IDrawableItem>()) {
    item.Draw();
}

, Nanook , , , , :

foreach(var item in Items) {
     if(item is IDrawableItem) {
        ((IDrawable)item).Draw();
     }
}

, , :

public static IEnumerable<T> OfType<T>(this IEnumerable<TSource> source) {
    if(source == null) {
        throw new ArgumentNullException("source");
    }
    foreach(TSource item in source) {
        if(item is T) {
            yield return (T)item;
        }
    }
}

, , , , Items . , , OfType , , .

+11

:

  • .
  • DrawIfPossible() IItem. IDrawableItem Draw(), IItem() .

, - .

+1

All Articles