c# - 动态设置变量名称为文本框名称
问题描述
我目前正在做一个项目,在该项目中我创建了一个自定义计算器来保存您自己的公式。
有数字上下元素,允许用户在计算器中设置一定数量的变量。一旦列出了他们使用的变量,他们就会输入问题并将结果显示在输出文本框中。
我希望这个工作的方式是每个文本框都有一个变量。我希望将变量的名称动态更改为文本框中的文本。
在用户输入的问题中,它被设置为由计算机解决的字符串。
例如
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 loop和 Is it possible to dynamic name variables based off user input?
解决方案
首先,你不能这样做;变量和控件名称需要在编译时知道。但是,您可以使用字典或类似的工具,您可以在编译时或运行时创建键和值,并在运行时查询它们。
完整的人为示例:
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);
推荐阅读
- powershell - 带连接路径的点源
- python - 写入文件未显示我想要的内容
- ruby-on-rails - 如何使用 React to Heroku 部署 Ruby on Rails 后端 API
- javascript - Nodemailer 错误处理 (Node.js) 无法按预期工作。即使 **name inputfield** 为空,电子邮件仍然可以通过
- javascript - 条纹设置意图
- php - 在 WooCommerce 管理员订单列表中显示每个订单的变体名称
- react-native - 在应用程序加载时未使用 redux-persist 读取值
- java - 错误代码[20001];ORA-20001: ERROR-ORA-01722: 无效号码 ORA-06512
- javascript - 递归后多次触发 addEventListener
- firefox - 如何从 Firefox 的 URL 栏中删除右箭头?