object - TclOO:对象等于
解决方案
TclOO 在设计上没有为您定义平等系统;由于对象通常是可修改的,因此除了对象身份之外没有其他适用的自动概念,您只需比较对象的名称即可获得该名称(或 的结果info object namespace $theObj
,如果您非常偏执的话;我认为 Tcl 8.7 将提供更多选项,但尚未接受)。
如果你想定义一个你提议的平等系统,你可以这样做:
oo::class create PropertyEquals {
method equals {other} {
try {
set myProps [my properties]
set otherProps [$other properties]
} on error {} {
# One object didn't support properties method
return 0
}
if {[lsort [dict keys $myProps]] ne [lsort [dict keys $otherProps]]} {
return 0
}
dict for {key val} $myProps {
if {[dict get $otherProps $key] ne $val} {
return 0
}
}
return 1
}
}
然后你只需要properties
在你可能要比较的类上定义一个方法,并混合equals
上面的方法。
oo::class create Example {
mixin PropertyEquals
variable _x _y _z
constructor {x y z} {
set _x $x; set _y $y; set _z $z
}
method properties {} {
dict create x $_x y $_y z $_z
}
}
set a [Example new 1 2 3]
set b [Example new 2 3 4]
set c [Example new 1 2 3]
puts [$a equals $b],[$b equals $c],[$c equals $a]; # 0,0,1
请注意,Tcl 不像其他一些语言那样提供复杂的集合类(因为它具有类似数组和类似映射的开放值),因此不需要对象相等(或内容散列)框架来支持它。
推荐阅读
- javascript - 如何在 React 中使用外键将数据添加到我的数据库中
- r - r 循环用于过滤每一列
- sql - SQL GROUP BY 子句并在使用 AVG 的 DATESPAN 计算中获得浮点 2 精度
- javascript - 如何查看特定 JS 对象的可达性
- accelerometer - ADXL345 加速度计数据在 I2C 上的使用(Beaglebone Black)
- mongodb - MongoDB If 条件作为 gt 中的第二个字段
- python - Django:单击按钮后调用方法
- python - PyOpenGL 如何选择颜色来绘制每个形状?
- java - Gson 自定义反序列化器从另一个字段派生一个字段的类型
- angular - 如何在 Protractor 中配置后端 URL(前端项目)