Itcl 配置方法:如何在配置脚本中使用 public 变量?

Itcl configure method: How to use public variables with a config script?

在 Itcl 中使用 public 个变量的配置脚本的正确方法是什么?

我的意思是,这就是我想要做的:

class MyClass {

    private variable myVar

    public method setMyVar {arg} {
        if {![string is integer -strict $arg]} {
            return -code error "argument $arg is not an integer"
        }
        set myVar $arg
    }
}

至少,这就是我用 C++ 编写 setter 方法的方式。首先,检查参数,如果有效,则将其分配给私有变量。如果参数无效,则保持对象状态不变。

现在,我决定使用 Itcl 的 configure 机制重写代码,而不是为我拥有的每个内部状态变量编写 getter 和 setter 方法。 (我喜欢按标准方式做事。)

class MyClass {
    public variable myVar 10 {
        if {![string is integer -strict $myVar]} {
            return -code error "new value of -myVar is not an integer: $myVar"
        }
    }
}

myObj configure -myVar "some string"

这种方法的问题是,即使参数无效,变量也会被赋值!并且没有(简单的)方法可以将其恢复为之前的值。

Itcl 配置脚本的正确使用方法是什么?我知道它们是为 Tk 小部件设计的,作为在值更改时更新 GUI 的一种方式,但是 Tk 小部件也需要验证它们的参数,不是吗?

我建议你升级到 Tcl 8.6 和 Itcl 4.0,当我尝试时它 Just Worked™:

% package req Itcl
4.0.2
% itcl::class MyClass {
    public variable myVar 10 {
        if {![string is integer -strict $myVar]} {
            # You had a minor bug here; wrong var name
            return -code error "argument $myVar is not an integer"
        }
    }
}
% MyClass myObj
myObj
% myObj cget -myVar
10
% myObj configure -myVar "some string"
argument some string is not an integer
% puts $errorInfo
argument some string is not an integer
    (error in configuration of public variable "::MyClass::myVar")
    invoked from within
"myObj configure -myVar "some string""
% myObj cget -myVar
10