繁体   English   中英

在类中将属性移动到另一个属性会引发异常“ System.InvalidCastException:'对象必须实现IConvertible。'”

[英]moving property to anther property in class throws exception “System.InvalidCastException: 'Object must implement IConvertible.'”?

我试图找到的将DynamicProperties属性移动到JSONdata属性的方法,因为当涉及DynamicProperties时,我具有此反射功能来完成这项工作,它会引发异常“ System.InvalidCastException:'对象必须实现IConvertible。'”有人可以帮忙我?

    public IHttpActionResult Get(ODataQueryOptions<Client> options)
    {
         if(queryNew.ElementType == typeof(Client)){}
        else //if (queryNew.ElementType.Name == "SelectSome`1")
        {
            var results = new List<Client>();
            try
            {
                foreach (var item in queryNew)
                {
                    var dict = ((ISelectExpandWrapper)item).ToDictionary();
                    var model = DictionaryToObject<Client>(dict);
                    results.Add(model);

                }

                return Ok(results);
            }
            catch (Exception)
            {

                throw;
            }
}

    private static T DictionaryToObject<T>(IDictionary<string, object> dict) where T : new()
    {
        T t = new T();
        PropertyInfo[] properties = t.GetType().GetProperties();

        foreach (PropertyInfo property in properties)
        {
            if (!dict.Any(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase)))
                continue;
            KeyValuePair<string, object> item = dict.First(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase));
            Type tPropertyType = t.GetType().GetProperty(property.Name).PropertyType;
            Type newT = Nullable.GetUnderlyingType(tPropertyType) ?? tPropertyType;
            if(dict.Any(x => x.Key.Equals("DynamicProperties", StringComparison.InvariantCultureIgnoreCase)))
            {
                object temp = JsonConvert.SerializeObject(item.Value, Formatting.Indented); //Convert.ChangeType(item.Value.ToString(), newT);
                t.GetType().GetProperty("JsonData").SetValue(t, temp, null);
            }
            object newA = Convert.ChangeType(item.Value, newT);
            t.GetType().GetProperty(property.Name).SetValue(t, newA, null);
        }
        return t;
    }

客户班

public class Client
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string ParticipantId { get; set; }
    public DateTime? BirthDate { get; set; }
    public int Gender { get; set; }
    public byte? Age { get; set; }
    public int Status { get; set; }
    public string Notes { get; set; }
    public DateTime CreatedDate { get; set; }
    public DateTime? UpdatedDate { get; set; }
    public DateTime? DeletedDate { get; set; }
    public bool IsDeleted { get; set; }
    public int? DefaultLanguageId { get; set; }
    public Guid UserId { get; set; }
    public string JsonData { get; set; }

    public virtual ICollection<ClientTag> ClientTags { get; private set; }

    protected IDictionary<string, object> _dynamicProperties;
    public IDictionary<string, object> DynamicProperties
    {
        get
        {
            if (_dynamicProperties == null)
            {
                if (this.JsonData == null)
                {
                    _dynamicProperties = new Dictionary<string, object>();
                }
                else
                {
                    _dynamicProperties = Mapper.Map<IDictionary<string, object>>(JObject.Parse(this.JsonData));
                }

                //_dynamicProperties.Source.ListChanged += (sender, e) => { this.AssessmentData = _dynamicProperties.Source.ToString(); };
            }

            return _dynamicProperties;
        }
    }
    public void UpdateJsonDataFromDynamicProperties()
    {
        this.JsonData = Mapper.Map<JObject>(_dynamicProperties).ToString();
    }
}

当您收到IConvertable错误时,表示您已尝试将一种类型分配给另一种类型。 例如,如果您尝试将文本框分配给字符串,则会收到错误消息,因为无法将对象分配给字符串,则必须使用Iconvertible 例如:

String.ToString();

隐式实现Iconvertible

我不能确切地说出您的代码在哪里失败,您也没有提到它,我只能告诉您在客户端方法中的某个地方,您试图分配两种不同的类型,但是您不能这样做。

在服务器和客户端类上都使用debug,并检查要在其中分配两种不同类型的位置,然后实现所需的Iconvertible,这意味着进行所需的转换。

此处代码中的唯一问题是,您尝试分配给不同的类型。

我的猜测是,这行引起了麻烦:

 if (this.JsonData == null)
                {
                    _dynamicProperties = new Dictionary<string, object>();
                }
                else
                {
                    _dynamicProperties = Mapper.Map<IDictionary<string, object>>(JObject.Parse(this.JsonData));
                }

实际上,当您试图将_dynamicProperties分配给字典对象时,您将_dynamicProperties声明为IDictionary对象。

字典和字典对象之间有细微的差别,它们不是同一类型。 这是需要完成的更改:

 if (this.JsonData == null)
                    {
                        _dynamicProperties = new IDictionary<string, object>();
                    }
                    else
                    {
                        _dynamicProperties = Mapper.Map<IDictionary<string, object>>(JObject.Parse(this.JsonData));
                    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM