首页 > 解决方案 > TclOO:对象等于

问题描述

TclOOobject equals实现的惯用模式是什么?

也许比较所有属性的串联排序列表

Scala案例类有类似物吗?

标签: objecttclequals

解决方案


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


推荐阅读