转换字符串类型,其中Type是一个变量 [英] Convert String to Type, where Type is a variable

查看:268
本文介绍了转换字符串类型,其中Type是一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个标准的方法来处理填充基于在cookie中,被用作用户的默认搜索标准存储值的视图模式。



我有问题,当涉及到转换字符串cookie值的属性类型,因此视图模型可以适当地更新。收到以下错误:

 从'System.String'到'System.Reflection.RuntimePropertyInfo'无效的演员。 

下面是我:

 公共TViewModel GetUserSearchCriteriaDefaults< TViewModel>(TViewModel视图模型)
式TViewModel:类
{$ b $型b型= viewModel.GetType();
串的className = viewModel.GetType()名称;
的PropertyInfo []属性= type.GetProperties();

如果(Request.Cookies时[类名]!= NULL)
{
串rawValue;

的foreach(在属性中的PropertyInfo财产)
{
如果(!String.IsNullOrEmpty(Request.Cookies时[类名] [property.Name))
$ { b $ b rawValue = Server.HtmlEncode(Request.Cookies时[类名] [property.Name]);
类型属性类型= property.GetType();
VAR convertedValue = Convert.ChangeType(rawValue,属性类型); < ----从这一行
property.SetValue(视图模型,convertedValue)错误;
}
}
}

返回视图模型;
}


解决方案

改变

 键入属性类型= property.GetType(); 



 键入属性类型= property.PropertyType; 

使用的GetType(),你得到的键入属性
和财产的PropertyInfo 的一个实例。


I am attempting to create a standard method to handle populating a view model based on stored values in a cookie, that are used as user defaults for search criteria.

I am having issues when it comes to converting the string cookie values to the property type so the view model can be updated appropriately. Getting the following error:

Invalid cast from 'System.String' to 'System.Reflection.RuntimePropertyInfo'.

Here is what I have:

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;
}

解决方案

change

Type propertyType = property.GetType();

to

Type propertyType = property.PropertyType;

Using GetType(), you get the type of property. And property is an instance of PropertyInfo.

这篇关于转换字符串类型,其中Type是一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆