【问题标题】:Dynamically convert object based on property type根据属性类型动态转换对象
【发布时间】:2015-11-25 21:08:03
【问题描述】:

我有一个 JObject,我正在从代表自定义对象 Adjuster 的 HTTP 帖子中的 JSON 字符串反序列化它。

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

我的问题是无法将 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;
    }

【问题讨论】:

标签: c#


【解决方案1】:

您可以像这样使用Convert.ChangeType 来做到这一点:

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

【讨论】:

【解决方案2】:

见: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)));
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    • 2013-02-19
    • 2018-10-13
    • 2021-03-18
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多