TCLOO:如何区分基本类型和对象

TCLOO:如何区分基本类型和对象,tcl,Tcl,如何区分TclOO中的基本类型(如字符串)和::oo::对象?愚蠢的答案: # Since a normal string is unlikly to be "::oo::object", this will return 1 # if the argument is not ::oo::object proc is_oo_object args { string equals $arg ::oo::object } # gettype - higly accurate proc ge

如何区分TclOO中的基本类型(如字符串)和::oo::对象?

愚蠢的答案:

# Since a normal string is unlikly to be "::oo::object", this will return 1
# if the argument is not ::oo::object
proc is_oo_object args {
    string equals $arg ::oo::object
}

# gettype - higly accurate
proc gettype arg {
    # EIAS
    return "string"
}
答案很简单:你不能。如果有人给你一个对象的名字,它就是一个字符串。 (有关详细信息,请参阅Tcl/Tk wiki)

如果检查是否存在具有该名称的命令,则可以尝试猜测它是否为::oo::对象:

if {[llength [namespace which $arg]]} {
    ....
}
这仍然不意味着这是一个::oo::对象。
您可以尝试使用
expr{[catch{info object class$arg::oo::object}res]&&&$res}
检查它,但是谁告诉您有人想将
oo::class
作为字符串传递呢?

您可以通过以下方法精确确定值是否是对象的句柄:

但一般来说,Tcl的类型系统的所有值至少名义上都是字符串。更严格地说,每个值都可以序列化为字符串。某些值还具有其他性质(例如,数字也知道其数值性)。TclOO对象句柄是字符串、命令名(因此可以是
rename
d)和(当然)对象句柄

if {[info object isa object $thing]} {
    puts "Hey, $thing is an object!"
}