簡體   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