0

嘿伙计们,我想知道如何访问一些变量,比如文本,我的意思是像 ex。以下

string variable1;
string variable2;
methodName(int variablenum){
   //Let's say the int is 1
   //How can I access variable1?
   //Sth like variable+"variablenum"
}

编辑:好吧,如果变量是variableAvariableB,我将如何访问它们?

4

2 回答 2

5

使用反射:

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);          
    }
}
于 2013-07-18T16:06:18.903 回答
1

也许数组可以为您提供所需的内容,但请注意可能出现的超出范围错误:

string [] variables = { "foo", "bar", "baz" }
string methodName( int variableIndex )
{
    return variables[ variableIndex ]; // bad if variable > 2
}
于 2013-07-18T16:11:39.417 回答