Itcl配置方法:如何在配置脚本中使用公共变量?
在Itcl中使用公共变量配置脚本的正确方法是什么 我是说,这就是我想做的:Itcl配置方法:如何在配置脚本中使用公共变量?,tcl,itcl,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" }
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++中编写一个SETER方法。首先,检查参数,如果参数有效,则将其分配给私有变量。如果参数无效,请保持对象状态不变
现在,我决定使用Itcl的configure
机制重写代码,而不是为我拥有的每个内部状态变量编写getter和setter方法。(我喜欢用标准的方式做事。)
这种方法的问题是,即使参数无效,变量也会被赋值!没有(简单的)方法将其恢复到以前的值
使用Itcl配置脚本的正确方法是什么?我知道它们是为Tk小部件设计的,作为在值发生变化时更新GUI的一种手段,但是Tk小部件也需要验证它们的参数,不是吗?我建议您升级到Tcl 8.6和Itcl 4.0,在那里它刚刚起作用™ 当我尝试时:
% 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
更正了
return-code error
中的var名称。奇怪的是,现在它在我的Tcl 8.5/Itcl 3.4安装中也运行良好。大约五天前我做了实验,我确信它不起作用;我一定犯了一些小错误。(可能是放置
和返回
组合,而不是返回-代码错误
?)但是,现在代码可以正确处理返回-代码错误
和错误
,并且字符串是
和字符串是-严格的
。无论如何,非常感谢您尝试我的代码并证明我错了。
% 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