如何使Dart对象/类可转位? [英] How does one make a Dart object/class indexable?
本文介绍了如何使Dart对象/类可转位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中,我可以通过重写 __ getitem __
使任何类支持索引:
class Test:
/ pre>
def __getitem __(self,key):
return self.data [key]
Dart是否有类似的结构?
解决方案假设
__ getitem __
可以使用indexing语法(object [index]
),允许您通过定义operator []
执行相同操作。示例:class Test {
var data = {
a :1,
b:2
};
operator [](index)=> data [index];
}
main(){
var t = new Test();
print(t [a]);
print(t [b]);
}
您还可以定义对
] =
:class Test {
地图数据= {
a:1,
b:2
};
operator [](index)=> data [index];
operator [] =(index,value){data [index] = value; }
}
main(){
var t = new Test();
print(t [a]);
print(t [b]);
t [c] = 3;
print(t [c]);
}
In Python I can make any class support indexing by overriding
__getitem__
like so:class Test: def __getitem__(self, key): return self.data[key]
Does Dart have a similar construct for this?
解决方案Assuming that the
__getitem__
thing lets you use the "indexing" syntax (object[index]
), yes, Dart lets you do the same by definingoperator []
. Example:class Test { var data = { "a": 1, "b": 2 }; operator [](index) => data[index]; } main() { var t = new Test(); print(t["a"]); print(t["b"]); }
You can also define the "opposite"
operator []=
:class Test { Map data = { "a": 1, "b": 2 }; operator [](index) => data[index]; operator []=(index, value) { data[index] = value; } } main() { var t = new Test(); print(t["a"]); print(t["b"]); t["c"] = 3; print(t["c"]); }
这篇关于如何使Dart对象/类可转位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文