itcl configure方法:如何使用配置脚本使用公共变量?

时间:2015-03-23 09:25:23

标签: tcl itcl

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

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

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方法的方法。首先,检查参数,如果验证,则将其分配给私有变量。如果参数无效,则保持对象状态不变。

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

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小部件也需要验证他们的参数,不是吗?

1 个答案:

答案 0 :(得分:2)

我建议您升级到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
相关问题