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]));
}
我该怎么做?
编辑:更改了代码以更准确地显示我想要做的事情。
答案 0 :(得分:5)
不知道做你想做的事情是不是一个好主意,但这应该有效:
((string[])GetType().GetField("tName").GetValue(this))[0] = "TheNewValue";
我认为将它分成多个语句是个好主意! ; - )
答案 1 :(得分:3)
字段的名称不是'tName [0]',而是'tName'。您需要将值设置为另一个数组,其0索引是您想要的值。
this.GetType().GetField("tName").SetValue(this, <Your New Array>));
答案 2 :(得分: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;
}
答案 3 :(得分:0)
为什么不这样做呢
tName[0] = "TheNewValue";
答案 4 :(得分:0)
您可以获取现有数组,修改它并将其设置回字段,如此...
string [] vals = (string [])this.GetType().GetField("tName").GetValue(this);
vals[0] = "New Value";
答案 5 :(得分:0)
我放弃并将表分成3个不同的变量。