I would suggest adding a recursive call to your method to set properties. I changed my method a bit because I donβt have a selected
object, it takes an object as a parameter
void UpdateValues<T>(T obj, Dictionary<string, string> values) { foreach (var value in values) { SetProperty(obj, value.Key, value.Value); } } public void SetProperty<T>( T obj, string valueKey, string value, Type type= null) { var typeToUse = type ?? typeof(T); var pointIndex = valueKey.IndexOf("."); if (pointIndex!=-1) { var subKey = valueKey.Substring(0, pointIndex); var fieldInfo = typeToUse.GetField(subKey); var propObj = fieldInfo.GetValue(obj) ?? Activator.CreateInstance(fieldInfo.FieldType); SetProperty(propObj, valueKey.Substring(pointIndex+1), value, fieldInfo.FieldType); fieldInfo.SetValue(obj, propObj); } else { var fieldInfo = typeToUse.GetField(valueKey); if (fieldInfo != null) fieldInfo.SetValue(obj, value); } }
It works even if you define
class test3 { public test2 data; }
and call
UpdateValues(t, new Dictionary<string, string>{{"age", "17"}}); UpdateValues(t2, new Dictionary<string, string> { { "data.age", "17" } }); UpdateValues(t3, new Dictionary<string, string> { { "data.data.age", "17" } });
The third parameter of the SetProperty
method is not very pleasant, I would have avoided it, but I donβt know how to solve it using generics, after creating with Activator
you get object
as a type, and the object does not have an age
field
You use Dictionary<string, string>
as a parameter that allows you to set only string fields, so you should assume that you have no other. Actually, this will work even if you use Dictionary<string, object>
, which I would suggest to do.