2010-07-09 4 views
3
public string[] tName = new string[]{"Whatever","Doesntmatter"}; 
string vBob = "Something"; 
string[] tVars = new string[]{"tName[0]","vBob","tName[1]"}; 

지금, TNAME [0]의 값을 변경하고자하지만 작업 나던에서 :C# GetType을() GetField 배열 위치

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

내가 어떻게 할 수 있습니까?

편집 : 내가하려는 일을보다 정확하게 보여주기 위해 코드가 변경되었습니다.

답변

0

나는 3 개의 다른 변수로 표를 포기하고 분할했다.

3

필드 이름이 'tName [0]'이 아니며 'tName'입니다. 값을 0으로 설정하는 다른 배열에 값을 설정해야합니다.

this.GetType().GetField("tName").SetValue(this, <Your New Array>)); 
0

tName[0] = "TheNewValue"; 
+0

/한숨 나는 분명히하기 위해 간단한 예를 만들었습니다. – Wildhorn

0

당신은, 기존의 배열을 얻을 그것을 수정하고 다시 지금과 같은 필드를 설정할 수 있습니다 ..

string [] vals = (string [])this.GetType().GetField("tName").GetValue(this); 
vals[0] = "New Value"; 
+0

어레이를 다시 설정할 필요가 없습니다. 제자리에서 수정하면 충분합니다. –

+0

마지막 라인이 정말로 필요하다고 생각합니까? – Achim

5
에게

이 몰라 만하지 왜 시도하려는 작업을 수행하는 것이 좋지만 작동해야하는 경우 :

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

여러 문장으로 나누는 것이 좋습니다. ;-)

1
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; 
}