在Dart中动态设置变量名称 [英] Dynamically setting variable name in Dart

查看:40
本文介绍了在Dart中动态设置变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Dart中将变量名称和值保存到JSON文件中.后来,我从该JSON文件中提取了名称和值,现在尝试使用该名称创建一个新变量.像这样:

I had saved a variables name and value to a JSON file in Dart. Later I extracted the name and value from that JSON file and now am trying to create a new variable with that name. Something like this:

var variableName= "firstName";
String variableName = "Joe";

这样:

String firstName = "Joe";

有没有办法做到这一点?

Is there a way to do this?

推荐答案

简短答案:否.

您无法在Dart中在运行时创建变量.编译器假定在编译程序(或任何单个方法)时所有变量都是可见的.

You cannot create variables at runtime in Dart. The compiler assumes that all variables are visible when the program (or any single method) is compiled.

在Dart中查找变量的方式是,如果词法范围中存在这样的变量,则"x"是指局部,静态或顶级变量,如果存在,则它是指"this.x"在名为"x"的词法范围内是变量.

The way variables are looked up in Dart is that "x" refers to a local, static or top-level variable, if there is such a variable in the lexical scope, and it refers to "this.x" if there is variable in the lexical scope named "x".

如果以后可以添加变量,则可以将"x"从含义"this.x"更改为其他含义.这样,已经编译的代码将不正确.

If you could add a variable later, you would be able to change "x" from meaning "this.x" to meaning something else. Already compiled code would then be incorrect.

这篇关于在Dart中动态设置变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆