我需要一种访问对象属性/获取器的通用方法。
在JavaScript中,这可以通过
完成const obj = {
foo: 'Hello World',
bar: 123
};
const propName = 'foo';
console.log(o[propName]); // "Hello World"
因此,如果我在Dart中有一个类,如下面的类,我将如何以通用方式访问属性?也许是因为运算符重载了?
class MyFooClass with ChangeNotifier {
String _someText = 'Hello World';
int _someNumber = 123;
get someText => _someText;
set someText(value) => _someText = value;
get someNumber => _someNumber;
set someNumber(value) => _someNumber = value;
}
var myFoo = MyFooClass();
print(myFoo['someText']); // The operator '[]' isn't defined for the class 'MyFooClass'
答案 0 :(得分:0)
可以使用dart:mirrors
(请注意,我删除了一些东西使其可以自行编译):
import 'dart:mirrors';
class MyFooClass {
String _someText = 'Hello World';
int _someNumber = 123;
get someText => _someText;
set someText(value) => _someText = value;
get someNumber => _someNumber;
set someNumber(value) => _someNumber = value;
operator [](String name) {
InstanceMirror i = reflect(this);
for (DeclarationMirror declMirror in i.type.declarations.values) {
if (declMirror.isPrivate) {
continue;
}
Symbol simpleName = declMirror.simpleName;
// It's not possible to get the name from a symbol directly: https://github.com/dart-lang/sdk/issues/28372
if (simpleName.toString() == 'Symbol("${name}")') {
return i.getField(simpleName).reflectee;
}
}
}
}
使用方式:
void main() {
var myFoo = MyFooClass();
print(myFoo['someText']); // 'Hello, World!'
print(myFoo['someNumber']); // 123
print(myFoo['some non existent thing']); // null
}
这是您想要的吗?
void main() {
var o = {'foo': 'Hello World', 'bar': 123};
var propName = 'foo';
print(o[propName]); // 'Hello World'
}