現時点では、コードはフィールド/プロパティ/配列へのパスを指定してオブジェクトのフィールド/プロパティをルートオブジェクトから取得します。リフレクションを使用して構造体の配列の一部である構造体のフィールドの値を設定する
//MyObject.MySubProperty.MyProperty
SetValue('MySubProperty/MyProperty', 'new value', MyObject);
上記の例では、「新しい価値」私はある構造体のフィールドの値を設定するためにリフレクションを使用することができませんよ
に「MyObjectを」オブジェクトの「MYPROPERTY」プロパティを設定します構造体は値の型(配列内)なので、構造体の配列の一部。ここで
は
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);
...
以下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; }
は私が成功し、通常のプロパティ/フィールドとリストの小道具/フィールドの値を設定する方法です...いくつかのテストクラス/構造体ですその後、私はmyObject.myStructArray [0] .myField = ''私の新しい値 'を返します。 myObject.myOtherStructArray [1] .myOtherField =' '私の新しい値」
私はすべてdは 'FieldInf.SetValue(foundObject、newValue);の代わりです。ライン
事前
おかげで、私のフィードバックを参照してください。あなたの答えは、構造が以下の通りであるためにうまくいくとは思わない... MyObject.myStructArray [0] .myField したがって、Array.SetValueメソッドを使用して – Mark
... 配列の構造体にフィールドの値を設定しようとしています – Mark
はい。あなたが構造体の配列を持っているときはいつでも、それが最善の方法です。それを新しいローカル構造体にコピーし、そのメンバを上書きするだけでそれを渡すことができます。 –