嘿伙计们,我想知道如何访问一些变量,比如文本,我的意思是像 ex。以下
string variable1;
string variable2;
methodName(int variablenum){
//Let's say the int is 1
//How can I access variable1?
//Sth like variable+"variablenum"
}
编辑:好吧,如果变量是variableA,variableB,我将如何访问它们?
使用反射:
public class Program
{
public static void Main(string[] args)
{
Test test = new Test();
test.MethodName(1);
}
}
public class Test
{
private string variable1 = "1";
private string variable2 = "2";
public void MethodName(int variablenum)
{
// .Instance because not static, .NonPublic because private
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
FieldInfo field = GetType().GetField("variable" + variablenum, flags);
string s = (string)field.GetValue(this);
}
}
也许数组可以为您提供所需的内容,但请注意可能出现的超出范围错误:
string [] variables = { "foo", "bar", "baz" }
string methodName( int variableIndex )
{
return variables[ variableIndex ]; // bad if variable > 2
}