gpt4 book ai didi

dart - Dart中的通用getter/setter?

转载 作者:行者123 更新时间:2023-12-03 03:59:18 24 4
gpt4 key购买 nike

我需要一种通用的方法来访问对象的属性/ getter 。

在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'

最佳答案

可以使用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'
}

关于dart - Dart中的通用getter/setter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58452921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com