c# - Add item to Generic List / Collection using reflection -


i want add item generic list using reflection. in method "dosomething", trying finish following line,

pi.propertytype.getmethod("add").invoke(??????) 

but getting different kinds of error.

below complete code

public class mybaseclass {             public int vechicleid { get; set; }         }     public class car:mybaseclass {     public string make { get; set; } }     public class bike : mybaseclass {     public int cc { get; set; } }         public class main  {     public string agencyname { get; set; }     public mybasecollection<car> lstcar {get;set;}      public void dosomething()     {         propertyinfo[] p =this.gettype().getproperties();         foreach (propertyinfo pi in p)         {             if (pi.propertytype.name.contains("mybasecollection"))             {                 //cln contains list<car>                 ienumerable<mybaseclass> cln = pi.getvalue(this, null) ienumerable<mybaseclass>;                  **//now using reflection want add  new car object this.mybasecollection**                 pi.propertytype.getmethod("add").invoke(??????)             }         }         } } 

any ideas / suggestion ?

i think want:

// cast ienumerable<mybaseclass> isn't helping you, why bother? object cln = pi.getvalue(this, null);  // create mybaseclassinstance.  // (how though, if don't know element-type?) mybaseclass mybaseclassinstance = ...  // invoke add method on 'cln', passing 'mybaseclassinstance' argument. pi.propertytype.getmethod("add").invoke(cln, new[] { mybaseclassinstance } ); 

since don't know element-type of collection going (could car, bike, cycle etc.) you're going find hard find useful cast. example, although collection definitely implement ilist<somemybaseclasssubtype>, isn't helpful since ilist<t> isn't covariant. of course, casting ienumerable<mybaseclass> should succeed, won't since doesn't support mutations. on other hand, if collection-type implemented non-generic ilist or icollection types, casting might come in handy.

but if you're sure collection implement ilist<car> (i.e. know element-type of collection beforehand), things easier:

// more useful cast. ilist<car> cln = (ilist<car>)pi.getvalue(this, null);  // create car. car car = ...  // cast helped! cln.add(car); 

Comments

Popular posts from this blog

Delphi Wmi Query on a Remote Machine -