I have a method in which I like to perform a few different casts using reflection mechanism.
private static T GetObject<T>(Dictionary<string, object> dict)
{
Type type = typeof(T);
var obj = Activator.CreateInstance(type);
foreach (var kv in dict)
{
var p = type.GetProperty(kv.Key);
Type t = p.PropertyType;
Type t2 = kv.Value.GetType();
if (t == t2)
{
p.SetValue(obj, kv.Value);
}
else if (p.PropertyType == typeof(object))
{
p.SetValue(obj, GetObject<type of p>((Dictionary<string, object>) kv.Value)); //???
}
else
{
p.SetValue(obj, (type of p)(kv.Value)); //???
}
}
return (T)obj;
}
The second cast could be solved by iterating over primitives using an IF
statement, but for the first cast it is a problem because a type can have a lot of properties of different types.
How can I detect dynamically the necessary cast/casts?
Aucun commentaire:
Enregistrer un commentaire