2010-07-09 107 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; 
}