- I want to use simple c # reflection code.
- value of the target dictionary may contain a dictionary.
- value is an object type, which is a generic property.
- 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