将String转换为Type,其中Type是变量

Cha*_*son 3 c# generics

我正在尝试创建一个标准方法来处理基于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)

Rap*_*aus 8

更改

Type propertyType = property.GetType();
Run Code Online (Sandbox Code Playgroud)

Type propertyType = property.PropertyType;
Run Code Online (Sandbox Code Playgroud)

使用GetType(),你得到的类型property.而财产就是一个例子PropertyInfo.