C # GetType (). GetField в позиции массива - PullRequest
3 голосов
/ 09 июля 2010
public string[] tName = new string[]{"Whatever","Doesntmatter"};
string vBob = "Something";
string[] tVars = new string[]{"tName[0]","vBob","tName[1]"};

Теперь я хочу изменить значение tName [0], но оно не работает с:

for(int i = 0; i < tVars.Lenght;++i)
{
    this.GetType().GetField("tVars[0]").SetValue(this, ValuesThatComeFromSomewhereElse[i]));
}

Как я могу это сделать?

РЕДАКТИРОВАТЬ: Изменен код, чтобы показать более точно, что я пытаюсь сделать.

Ответы [ 6 ]

5 голосов
/ 09 июля 2010

Не знаю, будет ли хорошей идеей делать то, что вы пытаетесь сделать, но это должно сработать:

((string[])GetType().GetField("tName").GetValue(this))[0] = "TheNewValue";

Думаю, было бы неплохо разделить его на несколько утверждений! ; -)

3 голосов
/ 09 июля 2010

Имя поля не tName [0], это tName.Вам необходимо установить значение для другого массива, индекс 0 которого соответствует желаемому значению.

this.GetType().GetField("tName").SetValue(this, <Your New Array>));
1 голос
/ 09 июля 2010
SetUsingReflection("tName", 0, "TheNewValue");

// ...

// if the type isn't known until run-time...
private void SetUsingReflection(string fieldName, int index, object newValue)
{
    FieldInfo fieldInfo = this.GetType().GetField(fieldName);
    object fieldValue = fieldInfo.GetValue(this);
    ((Array)fieldValue).SetValue(newValue, index);
}

// if the type is already known at compile-time...
private void SetUsingReflection<T>(string fieldName, int index, T newValue)
{
    FieldInfo fieldInfo = this.GetType().GetField(fieldName);
    object fieldValue = fieldInfo.GetValue(this);
    ((T[])fieldValue)[index] = newValue;
}
0 голосов
/ 15 июля 2010

Я сдался и разделил таблицу на 3 разные переменные.

0 голосов
/ 09 июля 2010

Вы можете получить существующий массив, изменить его и установить обратно в поле следующим образом.

string [] vals = (string [])this.GetType().GetField("tName").GetValue(this); 
vals[0] = "New Value";
0 голосов
/ 09 июля 2010

Почему бы просто не сделать это

tName[0] = "TheNewValue";
...