C# 将字符串转换为类型,其中类型是变量

C# 将字符串转换为类型,其中类型是变量,c#,generics,C#,Generics,我试图创建一个标准方法来处理基于cookie中存储的值填充视图模型的问题,这些值用作搜索条件的用户默认值 在将字符串cookie值转换为属性类型以便可以适当更新视图模型时,我遇到了一些问题。获取以下错误: Invalid cast from 'System.String' to 'System.Reflection.RuntimePropertyInfo'. 以下是我所拥有的: public TViewModel GetUserSearchCriteriaDefaults<TViewMo

我试图创建一个标准方法来处理基于cookie中存储的值填充视图模型的问题,这些值用作搜索条件的用户默认值

在将字符串cookie值转换为属性类型以便可以适当更新视图模型时,我遇到了一些问题。获取以下错误:

Invalid cast from 'System.String' to 'System.Reflection.RuntimePropertyInfo'.
以下是我所拥有的:

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;
}
public TViewModel GetUserSearchCriteriaDefaults(TViewModel viewModel)
TViewModel:类的位置
{
Type Type=viewModel.GetType();
字符串className=viewModel.GetType().Name;
PropertyInfo[]properties=type.GetProperties();
if(Request.Cookies[className]!=null)
{
字符串值;
foreach(属性中的PropertyInfo属性)
{
如果(!String.IsNullOrEmpty(Request.Cookies[className][property.Name]))
{
rawValue=Server.HtmlEncode(Request.Cookies[className][property.Name]);
类型propertyType=property.GetType();
var convertedValue=Convert.ChangeType(rawValue,propertyType);change

使用
GetType()
,可以获得
属性的类型。

属性是
PropertyInfo

的一个实例,我知道您正试图使其成为超级泛型,但这似乎只允许您在cookie中存储任何类的单个实例。乍一看,这可能符合您的需要,但在我看来,这有点违背了成为超级泛型的目的。为什么不创建一个字符串到v查看您需要的类的模型适配器,然后可能使用工厂将它们从cookie中挖掘出来?这会更“有意”(因为没有更好的术语)并且更不容易…奇怪?
Type propertyType = property.GetType();
Type propertyType = property.PropertyType;