相关疑难解决方法(0)

使用Type对象将Object类型的对象转换为另一种类型

有一个像这样的对象:

object integerObject=1;
Run Code Online (Sandbox Code Playgroud)

和这样的对象:

Type integerType=typeof(Int32);
Run Code Online (Sandbox Code Playgroud)

如何将integerType对象用于将integerObject强制转换为Int32类型

.net c# casting

3
推荐指数
1
解决办法
720
查看次数

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

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

c# generics

3
推荐指数
1
解决办法
1021
查看次数

标签 统计

c# ×2

.net ×1

casting ×1

generics ×1