Setting a field on an object that is a property in a class using reflection in .NET -
i have following class structure (pseudocode):
class { property string who; property string where; } class b { property information; } class c { property string who; } i trying find out how set set b.a.who = c.who using reflection in .net 4.0.
thanks!
well, isn't difficult sort of correctly, messy if wanted argument-validation, graceful error-handling etc. here's example should highlight technique (no checks):
static void setbsaswhotocswho(object b, object c) { // cswho = c.who object cswho = c.gettype().getproperty("who").getvalue(c, null); // = b.information object = b.gettype().getproperty("information").getvalue(b, null); // a.who = cswho a.gettype().getproperty("who").setvalue(a, cswho, null); } you need sorts of checks in above code make robust. if tell why want use reflection accomplish task. depending on scenario, there may solutions more appropriate, such as:
- the obvious type-safe code.
- casting necessary, followed type-safe code.
- generating delegate constructing , compiling expression-tree.
- the use of
dynamic. - automapper , other libraries.
Comments
Post a Comment