首页 > 解决方案 > 动态设置变量名称为文本框名称

问题描述

我目前正在做一个项目,在该项目中我创建了一个自定义计算器来保存您自己的公式。

数字上下元素,允许用户在计算器中设置一定数量的变量。一旦列出了他们使用的变量,他们就会输入问题并将结果显示在输出文本框中。

我希望这个工作的方式是每个文本框都有一个变量。我希望将变量的名称动态更改为文本框中的文本。

在用户输入的问题中,它被设置为由计算机解决的字符串。

例如

var unnamedVarForTextbox1;

//pseudo code
unnamedVarForTextbox1.name = textbox1.Text; //let's say var1 is l for length (user input)
unnamedVarForTextbox2.name = textbox2.Text; //let's say var2 is w for width (user input)
unnamedVarForTextbox3.name = textbox3.Text; //let's say var3 is h for height (user input)

string userProblem = problem.Text;
//problem.Text is l*w*h (so volume)

//Displays solved problem in output textbox
output.text = userProblem;

我该怎么做?如果还有其他方法可以实现我的目标,或者如果您需要任何照片,请告诉我,并提前感谢您。

以下是一些相关度较低的网站: swift / changed name of variable in loopIs it possible to dynamic name variables based off user input?

标签: c#variablesdynamiccalculator

解决方案


首先,你不能这样做;变量和控件名称需要在编译时知道。但是,您可以使用字典或类似的工具,您可以在编译时或运行时创建键和值,并在运行时查询它们。

完整的人为示例:

private Dictionary<string,string _store = new Dictionary<string,string();

...


_store.Add(textbox1.Text,someValue);


...

if(_store.TryGetValue(textbox1.Text,out var someValue)
   Debug.WriteLine(someValue);

推荐阅读