将字符串转换为对象中的类型

本文关键字:类型 对象 字符串 转换 | 更新日期: 2023-09-27 18:17:14

我必须实现的代码从网页的Ajax调用中获取发布的数据列表。

我知道我需要更新的对象,但是每个字段/值对都是作为字符串值出现的,而不是作为它们正确的类型。

所以我试图找出属性的类型,将值转换为新类型,然后使用反射将其应用于字段。

然而,对于字符串以外的任何内容,我都得到以下错误:

Invalid cast from 'System.String' to 'System.TimeSpan'.

我尝试转换的代码是;

    public void Update<T>(string fieldName, string fieldValue)
    {
        System.Reflection.PropertyInfo propertyInfo = typeof(T).GetProperty(fieldName);
        Type propertyType = propertyInfo.PropertyType;
        var a = Convert.ChangeType(fieldValue, propertyType);
    }

目标对象也是。

将字符串转换为对象中的类型

没有适用于所有类型的绝对答案。但是,你可以使用TypeConverter而不是Convert,它通常工作得更好。例如,有一个TimeSpanConverter:

public void Update<T>(string fieldName, string fieldValue)
{
    System.Reflection.PropertyInfo propertyInfo = typeof(T).GetProperty(fieldName);
    Type propertyType = propertyInfo.PropertyType;
    TypeConverter converter = TypeDescriptor.GetConverter(type);
    if (converter.CanConvertFrom(typeof(string)))
    {
        var a = converter.ConvertFrom(fieldValue, type);
        ...
    }
}

在MVC(和。net一般)中处理JSON,我使用JSON.NET。它在ASP中是开箱即用的。NET MVC 4项目模板,可以在NuGet上使用。反序列化JSON字符串内容(通常)非常简单:

JsonConvert.DeserializeObject<Customer>(json);

如果传递的JSON不是一个序列化模型,你可以创建一个代码模型来匹配JSON。

如果这在您的场景中不起作用,您可以尝试Convert类,如果您知道类型,它具有转换选项:

Convert.ToInt32(stringValue);

ChangeType方法,如果它是动态的:

Convert.ChangeType(value, conversionType);

为了使用Convert,类型需要为IConvertible

从MSDN

 For the conversion to succeed, value must implement the IConvertible interface

TimeSpan没有实现它…

所以你可以在调用Convert或添加try{} catch{}之前检查