Last active
February 29, 2016 18:59
-
-
Save AdamLJohnson/0a9e73c2e7de3df49711 to your computer and use it in GitHub Desktop.
Recursive SetProperty
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Reflection; | |
public class RecursiveSetProperty | |
{ | |
/// <summary> | |
/// Sets the property of an object recursively. | |
/// </summary> | |
/// <param name="target">The target object.</param> | |
/// <param name="field">The field.</param> | |
/// <param name="value">The value.</param> | |
public static void SetProperty(object target, string field, object value) | |
{ | |
string[] bits = field.Split('.'); | |
if (bits.Length == 1) | |
{ | |
PropertyInfo prop = target.GetType().GetProperty(bits[0]); | |
if (prop != null) | |
prop.SetValue(target, value); | |
} | |
else | |
{ | |
PropertyInfo propertyToGet = target.GetType().GetProperty(bits[0]); | |
if (propertyToGet != null) | |
{ | |
var obj = propertyToGet.GetValue(target, null); | |
SetProperty(obj, string.Join(".", bits.Skip(1)), value); | |
} | |
} | |
} | |
public static void Main() | |
{ | |
var testObj = new Level(); | |
SetProperty(testObj, "Text", "Hello One"); | |
SetProperty(testObj, "NextLevel", new Level()); | |
SetProperty(testObj, "NextLevel.Text", "Hello Two"); | |
SetProperty(testObj, "NextLevel.NextLevel", new Level()); | |
SetProperty(testObj, "NextLevel.NextLevel.Text", "Hello Three"); | |
Console.WriteLine(testObj.Text); | |
Console.WriteLine(testObj.NextLevel.Text); | |
Console.WriteLine(testObj.NextLevel.NextLevel.Text); | |
} | |
} | |
public class Level | |
{ | |
public string Text {get; set;} | |
public Level NextLevel {get; set;} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment