c# - How to cast a list of concrete classes which implement an interface -
i have interface ianimal , 2 classes(dog, cat), both implement interface.
public interface ianimal { int age { get; set; } } public class dog : ianimal { public int age { get; set; } } public class cat : ianimal { public int age { get; set; } }
also, have animalsmanager class shown in code below.
public class animalsmanager { private readonly list<dog> _dogs = new list<dog>(); private readonly list<cat> _cats = new list<cat>(); public void settargetanimalsage(bool isdog, int age) { if (isdog) { setanimalsage(_dogs, age); } else { setanimalsage(_cats, age); } } private static void setanimalsage<t>(ienumerable<t> animals, int age) t : class, ianimal { foreach (var animal in animals) { animal.age = age; } } }
in method settargetanimalsage, setanimalsage used twice depending on value of isdog argument. i'd unite these 2 usages 1, following codes not compile.
// not compile. // var animals = isdog ? _dogs : _cats; // var animals = isdog ? _dogs list<ianimal> : _cats list<ianimal>; setanimalsage(animals, age);
how possible handle 1 of lists of dogs , cats list of ianimal?
you can't have ilist<t>
because ilist<t>
not covariant ienumerable<t>
covariant. can cast ienumerable<t>
, should work.
for example, following code should work:
public void settargetanimalsage(bool isdog, int age) { var animals = isdog ? (ienumerable<ianimal>)_dogs : _cats; setanimalsage(animals, age); }
Comments
Post a Comment