Need to use a String as a command.
-
I've got something like this String[] thing = {"name", "number"} int count = 0 for (count < 3; count++) { String command = "this." + thing[count]; command = input.readline(); } this.name and this.number are datatypes I've created and need to dynamically get access to to create entries. Unfortunatly I dont know how to get c# to use command literally, rather then just overwrite the string. Anyone got this figured out? Thanks!
-
I've got something like this String[] thing = {"name", "number"} int count = 0 for (count < 3; count++) { String command = "this." + thing[count]; command = input.readline(); } this.name and this.number are datatypes I've created and need to dynamically get access to to create entries. Unfortunatly I dont know how to get c# to use command literally, rather then just overwrite the string. Anyone got this figured out? Thanks!
Reflection is your friend:
for (int count = 0;count < thing.Length; count++)
{
FieldInfo info = this.GetType().GetField(thing[count], BindingFlags.NonPublic);
info.SetValue(this, input.readline());
}Note that with
BindingFlags.NonPublic
I assume that both variables are declared private. If not, take a look at the help for theGetField
method and theBindingFlags
enumeration and you should be able to figure out what needs to be changed.
"Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning." - Rick Cook