Dynamic variable in C#?

前端 未结 5 668
猫巷女王i
猫巷女王i 2020-11-30 12:00

Is it possible to use a dynamic variable (not sure about naming) in C#?

In PHP, I can do

$var_1 = \"2\";
$var_2 = \"this is variable 2\";

$test = ${         


        
5条回答
  •  猫巷女王i
    2020-11-30 12:03

    No, basically. The compiler doesn't guarantee that method variables will exist (in their form as written), or with names...

    If they were fields (instance or static), then you could use reflection to get the values; but not method variables. For what you want, perhaps use a dictionary as a substitute?

    var vars = new Dictionary();
    vars["var_1"] = "2";
    vars["var_2"] = "this is variable 2";
    
    Console.WriteLine(vars["var_" + vars["var_1"]]);
    

提交回复
热议问题