2010-07-09 105 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'。您需要將該值設置爲另一個數組,其索引是您想要的值。

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

爲什麼不只是這樣做

tName[0] = "TheNewValue"; 
+0

/感嘆我簡單地說明了我的例子。 – Wildhorn 2010-07-09 13:39:03

0

你可以得到現有的陣列,修改它,並把它設回像這樣的領域..

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

您不需要重新設置陣列 - 在位置修改就足夠了 – 2010-07-09 13:40:49

+0

您認爲最後一行是否真的需要? – Achim 2010-07-09 13:41:36

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