Skip to content

Instantly share code, notes, and snippets.

@codewings
Last active December 19, 2015 12:48
Show Gist options
  • Save codewings/5957008 to your computer and use it in GitHub Desktop.
Save codewings/5957008 to your computer and use it in GitHub Desktop.
Get/Set the value of a property in arbitrary depth of an object by reflection.
class Reflector
{
public static object SetValue(object target, string path, object value)
{
Stack<PropertyInfo> s1 = new Stack<PropertyInfo>();
Stack<object> s2 = new Stack<object>();
string[] properties = path.Split('.');
Type type = target.GetType();
object parent = target;
for (int level = 0; level < properties.Length; ++level)
{
if (type == null)
break;
PropertyInfo property = type.GetProperty(properties[level]);
type = property == null ? null : property.PropertyType;
if (level < properties.Length - 1)
{
s1.Push(property);
s2.Push(parent);
parent = property.GetValue(parent, new object[] { });
}
else
{
property.SetValue(parent, value, new object[] { });
for (int i = 0; i < s1.Count; ++i)
{
PropertyInfo a = s1.Pop();
object b = s2.Pop();
a.SetValue(b, parent, new object[] { });
parent = b;
}
}
}
return target;
}
public static object GetValue(object target, string path)
{
string[] properties = path.Split('.');
Type type = target.GetType();
object parent = target;
for (int level = 0; level < properties.Length; ++level)
{
if (type == null)
break;
PropertyInfo property = type.GetProperty(properties[level]);
type = property == null ? null : property.PropertyType;
if (level < properties.Length - 1)
{
parent = property.GetValue(parent, new object[] { });
}
else
{
return property.GetValue(parent, new object[] { });
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment