有一个像这样的对象:
object integerObject=1;
Run Code Online (Sandbox Code Playgroud)
和这样的对象:
Type integerType=typeof(Int32);
Run Code Online (Sandbox Code Playgroud)
如何将integerType对象用于将integerObject强制转换为Int32类型
我正在尝试创建一个标准方法来处理基于cookie中存储的值填充视图模型,这些值用作搜索条件的用户默认值.
在将字符串cookie值转换为属性类型时遇到问题,因此可以适当地更新视图模型.收到以下错误:
Invalid cast from 'System.String' to 'System.Reflection.RuntimePropertyInfo'.
Run Code Online (Sandbox Code Playgroud)
这是我有的:
public TViewModel GetUserSearchCriteriaDefaults<TViewModel>(TViewModel viewModel)
where 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 from this line
property.SetValue(viewModel, convertedValue);
}
}
}
return viewModel;
}
Run Code Online (Sandbox Code Playgroud)