c# - Convert String to Type, where Type is a variable -


i attempting create standard method handle populating view model based on stored values in cookie, used user defaults search criteria.

i having issues when comes converting string cookie values property type view model can updated appropriately. getting following error:

invalid cast 'system.string' 'system.reflection.runtimepropertyinfo'. 

here have:

public tviewmodel getusersearchcriteriadefaults<tviewmodel>(tviewmodel viewmodel)         tviewmodel : class {     type type = viewmodel.gettype();     string classname = viewmodel.gettype().name;     propertyinfo[] properties = type.getproperties();      if (request.cookies[classname] != null)     {         string rawvalue;          foreach (propertyinfo property in properties)         {             if (!string.isnullorempty(request.cookies[classname][property.name]))             {                 rawvalue = server.htmlencode(request.cookies[classname][property.name]);                 type propertytype = property.gettype();                 var convertedvalue = convert.changetype(rawvalue, propertytype); <---- error line                 property.setvalue(viewmodel, convertedvalue);             }         }     }      return viewmodel; } 

change

type propertytype = property.gettype(); 

to

type propertytype = property.propertytype; 

using gettype(), type of property. , property instance of propertyinfo.


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -