mardi 7 mars 2017

c# Convert dictionary to object. Better way

  1. I want to use simple c # reflection code.
  2. value of the target dictionary may contain a dictionary.
  3. value is an object type, which is a generic property.
  4. What should I do?

target

    static public T ToObject<T>(Dictionary<string, object> target) where T : class, new()
    {
        var obj = new T();
        foreach (var data in target)
        {
            var field = obj.GetType().GetField(data.Key);
            if (field.FieldType.Equals(typeof(Dictionary<string, long>)))
            {
                field.SetValue(obj, PaseDictionaryStringAnd<long>(data.Value));
            }
            else if (field.FieldType.Equals(typeof(Dictionary<string, double>)))
            {
                field.SetValue(obj, PaseDictionaryStringAnd<double>(data.Value));
            }
            else
            {
                field.SetValue(obj, data.Value);
            }
        }

        return obj;
    }

    static Dictionary<string, T> PaseDictionaryStringAnd<T>(object data)
    {
        var tempDic = new Dictionary<string, T>();
        foreach (var val in (Dictionary<string, object>)data)
        {
           tempDic[val.Key] = (T)val.Value;
        }
        return tempDic;
    }





Aucun commentaire:

Enregistrer un commentaire