c# - Setting Values on a derived class from the base class constructor using Reflection -
i have 2 classes this:
public abstract class mybase { protected mybase(){ initialize(); } protected idictionary<string,string> _data; private void initialize() { // use reflection properties // of derived class (e.g., call new myderived() // want know names "hello" , "id" here var data = getdatafrombackend(propertynamesfromderived); _data = data; } } public class myconcrete : mybase { public myconcrete(){ // possibly use reflection here hello = _data["hello"]; id = new guid(data["id"]); } public string hello {get;set;} public guid id {get; set;} }
as see, want constructor of base class know properties of derived class i'm instantiating.
now, seems huge , big code smell, let me give more background intentions, maybe there better way.
i have backend system stores key/value pairs, dictionary<string,string>
. want abstract away working backend system in way people can create classes properties keys backend system. when construct object, automatically load data system , initialize variables it.
in other words, i've reinvented serialization, except don't control backend system , rather make working painless. don't want callers have call initialize()
after constructing object, because in 100% of cases have initalize after constructing.
i don't want move initialize code derived classes, except string-to-business-object conversion.
would have use factory? or considered safe @ property names of derived class in base constructor? (don't care values , aren't initialized, need names).
or there better way altogether provide facade between dictionary of strings , concrete business object?
edit: .net 3.5, no system.dynamic make trivial :(
edit 2: after looking @ answers , thinking through more, guess question boils down now: calling gettype().getproperties() base constructor in order names of properties , if decorated attribute safe?
wait, let's stop here second , properly. it shouldn't mybase
's responsibility this.
so write class manages getting stuff out of backend you, , write method on class
t get<t>() t : new()
and make get
responsible reading dictionary out of backend , using reflection populate instance of t
. thus, say
var concrete = foo.get<myconcrete>();
this isn't hard, , it's right way it.
incidentally, code get
going like
t t = new t(); var properties = typeof(t).getproperties(); foreach(var property in properties) { property.setvalue(t, dictionary[property.name], null); } return t;
where dictionary
loaded key/value pairs. turns out there more optimal ways this, unless it's bottleneck wouldn't worry it.
Comments
Post a Comment