c# - Set field's value in Inherited class from base -
i think easy, don't know how :)
class base1 { public int x = 1; //... many other fields } class inherit1:base1 { int y = 5; ... } base bs=new base1(); // set many fields value of bs class bs.value1=5; bs.value15="sss"; //....set other fileds values inherit1 i1=new inherit1();
what fastest way set fields value inherited class i1 equal base fields value bs?
want this:
i1=bs;
and after init other field i1.
thank!
you can't assign base class intance derived type. need convert it.
so, first choise use automapper
. helps copy data object type other. automatically map proprties same names. @ end use such code f.e:
var derived = mapper.map<base, derived>(b);
, second choice write method , use reflection.
and use in constructor:
public class derived : base { public derived(base b) { setproperties(b); } private void setproperties(object mainclassinstance) { var bindingflags = bindingflags.public | bindingflags.instance; var mainclasstype = mainclassinstance.gettype(); memberinfo[] members = mainclasstype.getfields(bindingflags).cast<memberinfo>() .concat(mainclasstype.getproperties(bindingflags)).toarray(); foreach (var memberinfo in members) { if (memberinfo.membertype == membertypes.property) { var propertyinfo = memberinfo propertyinfo; object value = propertyinfo.getvalue(mainclassinstance, null); if (null != value) propertyinfo.setvalue(this, value, null); } else { var fieldinfo = memberinfo fieldinfo; object value = fieldinfo.getvalue(mainclassinstance); if (null != value) fieldinfo.setvalue(this, value); } } } }
then need:
base b = new base {...}; derived d = new derived(b);
additionally:
actually, better make setproperties
method extension method.
public static class objectextensions { public static void setproperties(this object newclassintance, object mainclassinstance) { var bindingflags = bindingflags.public | bindingflags.instance; var mainclasstype = mainclassinstance.gettype(); memberinfo[] members = mainclasstype.getfields(bindingflags).cast<memberinfo>() .concat(mainclasstype.getproperties(bindingflags)).toarray(); foreach (var memberinfo in members) { if (memberinfo.membertype == membertypes.property) { var propertyinfo = memberinfo propertyinfo; object value = propertyinfo.getvalue(mainclassinstance, null); if (null != value) propertyinfo.setvalue(newclassintance, value, null); } else { var fieldinfo = memberinfo fieldinfo; object value = fieldinfo.getvalue(mainclassinstance); if (null != value) fieldinfo.setvalue(newclassintance, value); } } } }
and, can use method as: this.setinheritedproperties(b);
Comments
Post a Comment