c# - How to modify a specific item in a collection using reflection -
i have item in collection need modify using reflection - i'm using reflection because don't know exact type of generic collection until runtime.
i know how use setvalue() method set value of property retrieved through collection, can use setvalue() set actual object inside collection?
ienumerable businessobjectcollection = businessobject ienumerable; foreach (object o in businessobjectcollection) { // want set "o" here replacement object in collection if // property on object equals type t = o.gettype(); propertyinfo identifierproperty = o.gettype().getproperty("identifier"); long entityid = (long)identifierproperty.getvalue(o, null); if (replacemententity.identifier == entityid) { // in case: set "o" replacemententity object // defined somewhere else. // can retrieve object using code, // set object setvalue? object item = businessobjectcollection.gettype().getmethod("get_item").invoke(businessobjectcollection, new object[] { 1 }); } }
well, use get_item
retrieve should able call set_item
set it:
businessobjectcollection.gettype().getmethod("set_item").invoke(businessobjectcollection, new object[] { 1, replacemententity });
note explode if collection not of type supporting indexed access.
Comments
Post a Comment