c# - How can I create instance of a type and set member values by name? -
i read xml list of commands, each command one
<read id="3" locationid="21"/>
or
<transform transformid="45" source="string"/>
and in xml deserializer i'm @ point i'm setting command objects , getting them ready execution.
type ctype = assembly.getexecutingassembly().gettype("processing." + command.name.tostring()); icommand commandobject = activator.createinstance(ctype);
when use activator.createinstance, there way assign members called 'id' , 'locationid' values 3 , 21? don't know in advance icommand on , each icommand has different members (except share 1 method)
like maybe (pseudocode)
commandobject = activator.createinstance(ctype); foreach( xmlattribute attribute in element){ commandobject <- setclassmember(attribute.name, attribute.value) }
dynamic variable types resolved in runtime already, if know commands contain id , locationid properties can like:
dynamic commandobject = activator.createinstance(ctype); commandobject.id = 3; commandobject.locationid = 21;
otherwise have use reflection check if exists first:
propertyinfo prop = commandobject.gettype().getproperty("id"); if(null != prop && prop.canwrite) { prop.setvalue(commandobject, 3, null); }
Comments
Post a Comment