c# - How can I get the base object of an object (not just the BaseType) -
i wondering how can actual base object of object? have base class named messagebase, , lot of classes inherit base class, inherited other classes in different depths. example:
some classes inherit this:
messagebase --> valuemessage --> doublevaluemessage
others that:
messagebase --> valuemessage --> [some class] --> [some other class] --> testmessage
what need this: have object of 1 of these inherited classes, let's instance of doublevaluemessage. don't know in advance type of object, know somehwere down nested inheritance, there base object (messagebase) properties need set.
now tried reference base object. tried valuemessage doublevaluemessage based upon, don't understand how.
i tried that:
public bool setpropertyvalue(object obj, string prop, object value) { var item = obj.gettype().getproperty(prop); //messagebox.show(obj.tostring()); if (item != null) { item.setvalue(obj, value); return true; } else { if (obj.base != null) { setpropertyvalue(obj.base, prop, mb); } } return false; }
the idea this: pass in object (e.g. of type doublevaluemessage), property want set (is base object property in first place?) , object needs replace given property, in case messagebase. thought idea recursively iterate down inheritance hierarchy until property need set found.
the problem is: .base
keyword not seem right way base object.
how can it? in advance help!
you can private property of base type using following code:
public bool setpropertyvalue(object obj, string prop, object value) { var item = obj.gettype().basetype.getproperty(prop, system.reflection.bindingflags.instance | system.reflection.bindingflags.nonpublic); //messagebox.show(obj.tostring()); if (item != null) { item.setvalue(obj, value); return true; } return false; }
see http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx more details on bindingflags.
for multiple layers of inheritance like:
public bool setpropertyvalue(object obj, string prop, object value) { var item = getbasetype(obj.gettype()).getproperty(prop, system.reflection.bindingflags.instance | system.reflection.bindingflags.nonpublic); //messagebox.show(obj.tostring()); if (item != null) { item.setvalue(obj, value); return true; } return false; } public type getbasetype(type type) { if (type.basetype != typeof(object)) { return getbasetype(type.basetype); } return type; }
Comments
Post a Comment