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不像其他一些语言那样提供复杂的集合类(因为它有类似数组和类似映射的开放值),因此不需要对象相等(或内容哈希)框架来支持这一点。