根据属性类型动态转换对象

本文关键字:转换 对象 动态 类型 属性 | 更新日期: 2023-09-27 18:10:31

我有一个jobobject,我要从一个HTTP post的JSON字符串中反序列化它,这个JSON字符串代表一个自定义对象Adjuster。

然后,我将该对象与数据库中已经存在的对象合并以创建更新后的对象。我这样做是通过反射循环通过属性和分配他们的属性名称匹配。

我的问题出现了,JValue不能隐式转换为目标类型,我必须手动转换它。是否有一种方法可以动态转换对象?我可以得到它需要转换成的类型

这是我的模型活页夹:

  public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        JObject jsonObj = JsonConvert.DeserializeObject(actionContext.Request.Content.ReadAsStringAsync().Result) as JObject;
        Adjuster dbAdjuster = new Adjuster();
        Type adjType = dbAdjuster.GetType();
        PropertyInfo[] props = adjType.GetProperties();
        dbAdjuster = AdjusterFactory.GetAdjuster(Convert.ToInt32(jsonObj["ID"].ToString()));
        foreach (var prop in jsonObj.Properties() )
        {
            foreach (PropertyInfo info in props)
            {
                if (prop.Name == info.Name && prop.Name != "ID")
                {
                    if (info.GetValue(dbAdjuster) is string)
                    {
                        info.SetValue(dbAdjuster, Convert.ToString(prop.Value));
                        break;
                    }
                    //continue for every type
                }
                else
                {
                    break;
                }
            }
        }
        bindingContext.Model = dbAdjuster;
        return true;
    }

根据属性类型动态转换对象

您可以这样使用Convert.ChangeType:

property.SetValue(item, Convert.ChangeType(valueToConvert, property.PropertyType));

参见:Generic type conversion FROM string

TConverter.ChangeType<T>(StringValue);  
public static class TConverter
{
    public static T ChangeType<T>(object value)
    {
        return (T)ChangeType(typeof(T), value);
    }
    public static object ChangeType(Type t, object value)
    {
        TypeConverter tc = TypeDescriptor.GetConverter(t);
        return tc.ConvertFrom(value);
    }
    public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter
    {
        TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
    }
}