c# - Casting and interface inheritance -
each item has interface, iitem
. this, there interface known idrawableitem
inherits item.
the code below, trying draw drawable item, cannot collection class stores accepts iitem
. can add inherits iitem
class, using other methods can achieved casting.
foreach (var item in items) { item.draw(); // casting go here. }
i know how cast, as
etc... acceptable? best practice?
just wondering if there other ways handle such scenarios.
use enumerable.oftype
extract elements of items
implement idrawableitem
:
foreach(var item in items.oftype<idrawableitem>()) { item.draw(); }
to address question nanook asked in comments above code translated code equivalent following:
foreach(var item in items) { if(item idrawableitem) { ((idrawable)item).draw(); } }
of course, there iterator behind scenes looks this:
public static ienumerable<t> oftype<t>(this ienumerable<tsource> source) { if(source == null) { throw new argumentnullexception("source"); } foreach(tsource item in source) { if(item t) { yield return (t)item; } } }
so, shows iterate through items
once. of course, there no requirement oftype
implemented above sensible thing do.
Comments
Post a Comment