c# - Casting object list which inherits type to new interface type list -
for example imagine have following interface , class configuration:
public interface ianimal { } public interface idog : ianimal { } public class animal : ianimal { }
then using above configuration in implementation this
list<ianimal> listofanimals = new list<animal>();
i wish cast list idog this:
list<idog> listofdogs = listofanimals.cast()<idog>.tolist();
i have tried
list<idog> listofdogs = listofanimals.cast()<ianimal>.cast()<idog>.tolist();
is possible, possible not 100% sure if can done or not??
currently recieve invalidcastexception
list<idog> listofdogs = listofanimals.cast<ianimal>().cast<idog>().tolist();
this work if listofanimals
idog
. believe looking oftype
.
list<idog> listofdogs = listofanimals.oftype<idog>().tolist();
also note ()
, <>
reversed. thing note items not idog
ignored , not returned.
update comment:
i lead believe can cast both ways when dealing inheritance of interfaces etc..eg: ianimal -> idog , idog -> ianimal
this true if of items implement idog
. can go , fro without issue. however, if have instance of animal
, cannot go idog
unless animal implements idog
.
imagine had animal, dog, , cat. dog , cat both animals. can go wanting animal. however, cannot explicitly give animal wanting dog or cat. need cast upwards. cast succeed if object correct type, fail if tried turn cat dog.
c# statically typed language. though there no method signatures differing between cat , dog , interface empty, not same thing.
public interface ianimal { } public interface idog : ianimal { } public interface icat : ianimal { } public class animal : ianimal { } public class dog : animal, idog { } public class cat : animal, icat { } animal animal = null; var dog = new dog(); var cat = new cat(); animal = dog; //success animal = cat; //success cat = (cat)animal; //success because animal cat. dog = (dog)animal; //fail because animal cat. //the above same attempting do: dog = cat;
wiki
Comments
Post a Comment