目前,我的代码使用反射成功地设置了对象的字段/属性/数组的值,给定了从根对象到字段/属性的路径。
例如
//MyObject.MySubProperty.MyProperty
SetValue('MySubProperty/MyProperty', 'new value', MyObject);
上面的示例将“MyObject”对象的“MyProperty”属性设置为“新值”
我无法使用反射在结构中设置字段的值,该结构是结构数组的一部分,因为该结构是值类型(在数组内)。
这是一些测试类/结构......
public class MyClass {
public MyStruct[] myStructArray = new MyStruct[] {
new MyStruct() { myField = "change my value" }
};
public MyStruct[] myOtherStructArray = new MyStruct[] {
new MyStruct() { myOtherField = "change my value" },
new MyStruct() { myOtherField = "change my other value" }
};
}
public struct MyStruct { public string myField; public string myOtherField; }
下面是我如何成功设置列表中普通属性/字段和道具/字段的值...
public void SetValue(string pathToData, object newValue, object rootObject)
{
object foundObject = rootObject;
foreach (string element in pathToData.Split("/"))
{
foundObject = //If element is [Blah] then get the
//object at the specified list position
//OR
foundObject = //Else get the field/property
}
//Once found, set the value (this is the bit that doesn't work for
// fields/properties in structs in arrays)
FieldInf.SetValue(foundObject, newValue);
}
object myObject = new MyClass();
SetValue("/myStructArray/[0]/myField", "my new value", myObject);
SetValue("/myOtherStructArray/[1]/myOtherField", "my new value", myObject);
之后我想要 myObject.myStructArray[0].myField = ''my new value" 和 myObject.myOtherStructArray[1].myOtherField = ''my new value"
我所需要的只是替换“FieldInf.SetValue(foundObject, newValue);” 线
提前致谢