c# - Cast Parent class to Child -


we have observablecollection<t> of 6 observablecollection list<parent> have different types of child classes.

what use generic method retrieve objects have same type, in other words retrieve list contains <t> children.

here source code

classes , b child classes of parent.

observablecollection<managertemplate> managerliststack = new observablecollection<managertemplate>(managertemplates);   class managertemplate {  public type _type { get; set; }  public observablecollection<parents> parentlist {get;set;} }  internal static list<managertemplate> managertemplates = new list<managertemplate>() {     new managertemplate{ list= new observablecollection<parent>(),type=typeof(a)},     new managertemplate{ list= new observablecollection<parent>(),type=typeof(b)} };  public static list<t> get<t>() t : parent {     /*(managerliststack.where(x => x._type == typeof(t)).first().list.cast<t>()).tolist(); -- try 1*/     /*(list<t>)(managerliststack.where(x => x._type == typeof(t)).first().list.cast<t>())* -- try 2*/     return  (managerliststack.where(x => x._type == typeof(t)).first().list.cast<t>()).tolist(); } 

using

(managerliststack.where(x => x._type == typeof(t)).first().list  list<t>) 

the returned list contains no elements.i 100% sure , have debugged list, , there elements inside.

using

(list<t>)(managerliststack.where(x => x._type == typeof(t)).first().list.cast<t>()) 

i error 'unable cast parent or b'

somelistofx list<y> never work. fact y derives x not mean list<y> derives list<x>! these 2 list types not compatible; 2 different types.

a list<parent> cannot cast list<child>, if contains items of type child because c# knows static types when compiles, not runtime types. list contain items not of type child.

by way, opposite doesn't work either. because if able cast list<child> list<parent>, add item of type parent or anotherchild list<parent>, since underlying list still of type list<child> f*** up! note, casting object not create new object (i.e. not transform object), tells c# consider being type. e.g. can child child = (child)parent; if know parent references child.


in

(list<t>)(managerliststack.where(x => x._type == typeof(t)).first().list.cast<t>()) 

cast<t> yields ienumerable<t> , cannot cast ienumerable<t> list<t>! enumerable not list.


what works is

list<y> listofy = listofx.cast<y>().tolist(); 

if x can cast y.


your third (uncommented) example in get<t> works:

return managerliststack     .where(x => x._type == typeof(t))     .first().list     .cast<t>()     .tolist(); 

Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -