Dynamic variable in C#?

2019-01-07 22:41发布

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 = ${"var_".$var_1};

echo $test;

output: this is variable 2;

Can we do this in C#?

5条回答
叛逆
2楼-- · 2019-01-07 23:06

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<string,object>();
vars["var_1"] = "2";
vars["var_2"] = "this is variable 2";

Console.WriteLine(vars["var_" + vars["var_1"]]);
查看更多
别忘想泡老子
3楼-- · 2019-01-07 23:14

You are not looking for simple arrays?

string[] myArray = new string[2];

myArray[0] = "2";
myArray[1] = "this is variable 2"

Otherwhise dictionary is the way to go.

查看更多
来,给爷笑一个
4楼-- · 2019-01-07 23:24

Not sure if this works with local variables (and most likely it doesn't since they're stored as indexes), but you could access class properties through reflection.

查看更多
劳资没心,怎么记你
5楼-- · 2019-01-07 23:27

If your var is a class field, then you can use the static GetField method from class Type to obtain field information, such as its current value.

查看更多
对你真心纯属浪费
6楼-- · 2019-01-07 23:28

In C#, you use dictionaries to associate values with strings.

查看更多
登录 后发表回答