Eiffel 中的泛型到整数转换
Generic to integer conversion in Eiffel
我有一些代码如下:
keys: LINKED_LIST[K]
...
test
local
tempK:K
tempI:INTEGER
do
...
across
keys as cursor
loop
tempK := cursor.item
if tempK ~ 1 then
tempI := tempK
end
end
...
end
"cursor.item" 是 "K" 的类型。但是里面的real value是整型的
因此,"if tempK ~ 1 then" 工作正常。但是 "tempI := tempK" 不起作用。
如何将 tempK 的 K 类型转换为整数?以便它可以编译?
在这种特殊情况下,如果您知道 tempK
是 1
,tempI := 1
就可以了。
如果想法是一旦存储在列表中的值是 INTEGER
类型就初始化 tempI
,有几种方法。一种是使用对象测试:
if attached {INTEGER} tempK as i then
tempI := i
end
但是,在这种情况下,对每个元素都进行测试,即效率低下。更改代码以在循环之前测试列表类型将有所帮助:
if attached {LINKED_LIST [INTEGER]} keys as integer_keys then
...
across
integer_keys as cursor
loop
tempI := cursor.item
end
...
end
如果循环中唯一的操作是赋值,等效代码是只取列表的最后一个元素:
...
if not keys.is_empty and then attached {LINKED_LIST [INTEGER]} keys as integer_keys then
tempI := integer_keys.last
end
...
除了专门化之外,还可以将代码概括为采用将传递密钥的通用代理,而客户端将提供处理密钥的过程。但这可能太多了,具体取决于您要解决的任务的目的。
我有一些代码如下:
keys: LINKED_LIST[K]
...
test
local
tempK:K
tempI:INTEGER
do
...
across
keys as cursor
loop
tempK := cursor.item
if tempK ~ 1 then
tempI := tempK
end
end
...
end
"cursor.item" 是 "K" 的类型。但是里面的real value是整型的
因此,"if tempK ~ 1 then" 工作正常。但是 "tempI := tempK" 不起作用。
如何将 tempK 的 K 类型转换为整数?以便它可以编译?
在这种特殊情况下,如果您知道 tempK
是 1
,tempI := 1
就可以了。
如果想法是一旦存储在列表中的值是 INTEGER
类型就初始化 tempI
,有几种方法。一种是使用对象测试:
if attached {INTEGER} tempK as i then
tempI := i
end
但是,在这种情况下,对每个元素都进行测试,即效率低下。更改代码以在循环之前测试列表类型将有所帮助:
if attached {LINKED_LIST [INTEGER]} keys as integer_keys then
...
across
integer_keys as cursor
loop
tempI := cursor.item
end
...
end
如果循环中唯一的操作是赋值,等效代码是只取列表的最后一个元素:
...
if not keys.is_empty and then attached {LINKED_LIST [INTEGER]} keys as integer_keys then
tempI := integer_keys.last
end
...
除了专门化之外,还可以将代码概括为采用将传递密钥的通用代理,而客户端将提供处理密钥的过程。但这可能太多了,具体取决于您要解决的任务的目的。