public static void SetValue(object baseObj, string fieldName, object value) { MemberInfo member = null; //The current field/property matched Type typeCurr = baseObj.GetType(); //The current type of the field/property matched object data = baseObj; //The previous object/property that matched string[] names = fieldName.Split('.'); foreach (string name in names){ //We are still going so get the current data object that we might //need to set if (member is PropertyInfo)data = (( PropertyInfo)member).GetValue(data, null); else if (member is FieldInfo)data = (( FieldInfo)member).GetValue(data); //Find the next property/field PropertyInfo prop = typeCurr.GetProperty(name); if (prop != null){ typeCurr = prop.PropertyType; member = prop; } else //Not a property so try the fields{ FieldInfo field = typeCurr.GetField(name); if (field != null){ typeCurr = field.FieldType; member = field; }; }; }; // if (member is FieldInfo) // data = ((FieldInfo)member).GetValue(data); if (member is PropertyInfo){ (( PropertyInfo)member).SetValue(data, value, null);} else{ //((FieldInfo)member).SetValue(data, value);(( FieldInfo)member).SetValue(data, value);}; } |
doesn't actually set the value...
I was given the following code to set a value in an object from a string like "Header.field.str". It seems to function correctly but never sets the value. Any help is much appreciated...

doesn't actually set the value...
hrh
baseObj.GetType().InvokeMember(name,
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.SetField | BindingFlags.Static,
null, baseobj, new object[] {value});
ScottLeo
public class AClass
{
public Nested
{
int nestedInt
}
int baseInt;
}
sounds like a need for recursion on the same method - do you need me to elaborate more
RedHedToo
Thanks,
Devin
cllard
Adam Friedman
Jakin
public static object GetValue(object obj, string path)
{
return TraverseObjectValue(obj, path.Split('.'), null);}
public static void SetValue(object obj, string path, object value){
object o = TraverseObjectValue(obj, path.Split('.'), value);}
public static object TraverseObjectValue(object lastobj, string[] paths, object value){
Type t = lastobj.GetType(); FieldInfo f = t.GetField(paths[0]); object o = f.GetValue(lastobj); if (paths.GetLength(0) > 1)//if not at end value{
string[] p = new string[paths.GetUpperBound(0)]; for (int i = 1; i < paths.GetLength(0); i++)p[i - 1] = paths
;
object oo = TraverseObjectValue(o, p, value); if (value != null)f.SetValue(lastobj, o);
return oo;}
else//if at end value{
if (value != null)f.SetValue(lastobj, value);
return o;}
}
I figured out that obtaining the object from the field was creating a new object instead of a reference. You'll see that I assigned the newly created object to the parent object to allow for the recursion.