c# - Cast fails from ICollection<TestCastChild> to ICollection<ICastBase> -
this question has answer here:
i'm using reflection property icollection<testcastchild>
, cast icollection<icastbase>
. testcastchild implement's icastbase. when try cast collection, cast fails. i'm sure i'm missing simple. can't see why fails.
public interface icastbase { int id { get; set; } } public interface icastchild : icastbase { string name { get; set; } } public abstract class testcastbase : icastbase { public int id { get; set; } } public class testcastchild : testcastbase, icastchild { public string name { get; set; } } public class testcastparent : testcastbase { public virtual icollection<testcastchild> children { get; set; } }
then test:
[testmethod] public void testcast() { var parent = new testcastparent(); parent.children = parent.children ?? new list<testcastchild>(); parent.children.add(new testcastchild{name = "a"}); parent.children.add(new testcastchild { name = "b"}); parent.children.add(new testcastchild { name = "c"}); var propinfos = parent.gettype().getproperties(); foreach (var propertyinfo in propinfos) { if (propertyinfo.propertytype.getmethod("add") != null) { var tmpval = propertyinfo.getvalue(parent); //this evaluates null var cast1 = tmpval icollection<icastbase>; //this evaluates null var cast2 = tmpval icollection<icastchild>; //this evaluates expected value var cast3 = tmpval icollection<testcastchild>; } } }
you cannot cast icollection<derived>
icollection<base>
, icollection<t>
not covariant.
if possible, cast icollection<dog>
icollection<mammal>
, add cat
collection, it's mammal
too.
what can do, cast ireadonlycollection<derived>
ireadonlycollection<base>
ireadonlycollection<out t>
covariant. if concrete collection type implements ireadonlycollection<out t>
(and list<t>
does) work fine, you'll read interface underlying collection. way, type safety still preserved.
note can use ireadonlylist<out t>
, inherits ireadonlycollection<out t>
, adds indexer.
Comments
Post a Comment