Dynamic variable in C#?

让人想犯罪 __ 提交于 2019-11-27 05:06:52

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

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"]]);

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!