i have following situation. lets receive list of string values. have assign values specific type properties in model. model example:
public int id { get; set; } public datetime? date { get; set; } there no problem in type conversion array of property types system.reflection , use convert.changetype(string value, type). however, can't assignt convert.changetype results model properties because returns object not desired type of value. short example of problem:
string s1 = "1"; string s2= "11-jun-2015"; propertyinfo[] matdetailsproperties = model.gettype().getproperties(); list<type> types = new list<type>(); foreach(var item in model) { types.add(item.propertytype); } model.id = convert.changetype(s1, types[0]); model.date = convert.changetype(s2, types[1]); this not work convert.changetype returns object , can't use (datetime)convert.changetype(...), that's "dirty code" have model 17 properties different types. perfect if use (type[0])convert.changetype(...) not possible in c#
you use reflection. how this?
var prop = model.gettype().getproperty("id"); var propvalue = convert.changetype(s1, types[0]); if (prop != null && prop.canwrite) { prop.setvalue(model, propvalue, null); }
Comments
Post a Comment