.net - C# Generics, casting generic list to known parent class? -


i'm trying cast list of objects parent using generics. have classes such as:

entity   node   otherclass 

where node/otherclass inherits entity. want this:

type totype = typeof(node); // not gotten way object fieldvalue = field.getvalue(item); list<entity> entities = (list<entity>)fieldvalue;  foreach (entity toent in entities) {     // code using toent using entity attributes... } 

i'm able field using fieldinfo reference i'm unable cast list. field value list of node reference seems it's unable cast list of entity should possible since inherits entity.

casting list of node instead works, want code able take list of otherclass. doesn't work cast list of objects, , casting each individual 1 entity.

i tried using makegenerictype, part of solution, couldn't work after quite while of trying.

thanks time!

a variation on other options, using covariance:

var sequence = (ienumerable<entity>) field.getvalue(item); var entities = sequence.tolist(); 

this relies on generic covariance of ienumerable<t>, work c# 4+ , .net 4+.

while list<node> isn't list<entity>, is ienumerable<entity>... above code takes advantage of.

of course if need iterate, don't need list<entity>:

var sequence = (ienumerable<entity>) field.getvalue(item); foreach (var entity in sequence) {     ... } 

but if do need create list<entity>, calling tolist() on ienumerable<entity> should fine.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -