对Flutter和Dart非常陌生,所以请原谅我的问题用词不当。
这是我的一个通用代码。
// Constructor class
class ctr {
String i;
ctr(String a){
this.a = a;
}
// New variables based on contsructor
var ctrA = ctr('a');
var ctrB = ctr('b');
var ctrC = ctr('c');
// Storing the variables based on constructor in an array
List ctrList = [ctrA, ctrB, ctrC]
void main() {
String match = 'ctrB';
for (var i = 0; i<ctrList.length; i++) {
if(match == ctrList.toString() {
print('The string of your match is ${ctrList[i].a}');
} else {
print('Error!);
}
}
}
当前的输出是 Error!
.相反,我所要找的是 a
.
正如你所看到的,我正在尝试迭代变量的 match
过基于前述构造函数存储变量的数组,如果匹配,则打印出它所匹配的构造函数中的值。runtimeType
只能让我得到源类的名称(将是 ctr
).
我试着用 toString()
但这也没有用。我需要的是将这些变量名转换成字符串并得到匹配的方法,但我不知道能做什么。
先谢谢大家的帮助!
在Dart中没有办法得到一个对象的名字。例如,C#有 nameof()
功能,但Dart没有类似的功能。
也就是说,不管你需要这个的原因是什么,可能有一个更简单的方法。所以你可以随时询问其他方法。
如果你只是想使用变量名作为一种标识符,也许可以看看Maps。
Map<String,String> x = {"ctrB" : "b"};
它们可以让你定义一个你想要的任何类型的键和值。
EDIT: 作为一个旁白,这个声明
class ctr {
String i;
ctr(String a){
this.a = a;
}
可以简化成这样。
class ctr {
String i;
ctr(this.i);
}
这就是你应该如何声明一个自定义对象的列表。
List<ctr> ctrList= [ ctrA , ctrB , ctrC ];
void main() {
String match = 'ctrB';
for (var index = 0; i<ctrList.length; i++) {
if(match == ctrList[index].i {
print('The string of your match is ${ctrList[i].a}');
} else {
print('Error!);
}}