gpt4 book ai didi

dart - 如何在 dart 中制作动态 getter/setter

转载 作者:行者123 更新时间:2023-12-04 14:27:52 24 4
gpt4 key购买 nike

我正在尝试重新创建 djangos QueryDict 功能并制作一个可以给定 Map 的对象,它是对象中的私有(private)变量,并且 getter/setter 用于动态地从 map 中提取。我已经设法重新创建它的 get() 方法,但我在动态获取值(value)时迷失了方向。这是我到目前为止所拥有的:

class QueryMap {
Map _data;

QueryMap(Map this._data);

dynamic get(String key, [var defaultValue]) {
if(this._data.containsKey(key)) {
return this._data[key];
} else if(defaultValue) {
return defaultValue;
} else {
return null;
}
}
}

这是关于它如何工作的 djangos 页面:
https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict.getitem

最佳答案

您可以覆盖 noSuchMethod (emulating functions)

@proxy
class QueryMap {
Map _data = new Map();

QueryMap();

noSuchMethod(Invocation invocation) {
if (invocation.isGetter) {
var ret = _data[invocation.memberName.toString()];
if (ret != null) {
return ret;
} else {
super.noSuchMethod(invocation);
}
}
if (invocation.isSetter) {
_data[invocation.memberName.toString().replaceAll('=', '')] =
invocation.positionalArguments.first;
} else {
super.noSuchMethod(invocation);
}
}
}
void main() {
QueryMap qaueryMap = new QueryMap();
qaueryMap.greet = "Hello Dart!";
print(qaueryMap.greet); //Hello Dart!
}

所述@PixelElephant 对于外部映射,您必须使用真实的方法名称作为映射键:

import 'dart:mirrors';
@proxy
class QueryMap {
Map _data;

QueryMap(this._data);

noSuchMethod(Invocation invocation) {
if (invocation.isGetter) {
var ret = _data[MirrorSystem.getName(invocation.memberName)];
if (ret != null) {
return ret;
} else {
super.noSuchMethod(invocation);
}
}
if (invocation.isSetter) {
_data[MirrorSystem.getName(invocation.memberName).replaceAll('=', '')] =
invocation.positionalArguments.first;
} else {
super.noSuchMethod(invocation);
}
}
}
void main() {
Map myMap = new Map();
myMap["color"] = "red";
QueryMap qaueryMap = new QueryMap(myMap);
qaueryMap.greet = "Hello Dart!";
print(qaueryMap.greet); //Hello Dart!
print(qaueryMap.color); //red
}

为避免使用镜像,您可以对符号的字符串序列化或转换外部映射键进行模式匹配:

@proxy
class QueryMap {
Map _data;

QueryMap(Map data) {
_data = new Map();
data.forEach((k, v) => _data[new Symbol(k).toString()] = v);
}

noSuchMethod(Invocation invocation) {
if (invocation.isGetter) {
var ret = _data[invocation.memberName.toString()];
if (ret != null) {
return ret;
} else {
super.noSuchMethod(invocation);
}
}
if (invocation.isSetter) {
_data[invocation.memberName.toString().replaceAll('=', '')] =
invocation.positionalArguments.first;
} else {
super.noSuchMethod(invocation);
}
}
}
void main() {
Map myMap = new Map();
myMap["color"] = "red";
QueryMap qaueryMap = new QueryMap(myMap);
qaueryMap.greet = "Hello Dart!";
print(qaueryMap.greet); //Hello Dart!
print(qaueryMap.color); //red
}

关于dart - 如何在 dart 中制作动态 getter/setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24254597/

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