简体   繁体   English

埃菲尔铁塔:古典式压铸开关结构,附带并检查

[英]Eiffel: classical typecasting switch structure with attached and inspect

What is the best practice to do something such as 做某事的最佳实践是什么

local
    l_pet: ANIMAL
do
    l_pet := catch_it_from_the_sky
    inspect l_pet
    when attached {DOG} l_pet as l_dog
        l_dog.eat (meat)
    when attached {FISH} l_pet as l_fish
        l_fish.eat (plants)
    else
        io.put_string ("Strange animal how do I feed him???")
    end
do

the compiler is complaining with the attached after when... 编译器与抱怨attached时,后...

Update: why such a need? 更新:为什么有这种需要?

because it just happened me to mess up with repeated copy-paste which is what a language tries to help avoiding. 因为碰巧我弄乱了重复的复制粘贴,这是一种语言试图避免的粘贴。 In the above case, the l_pet is written one time, with a N times if/else I'd have to write it as much times as ifs... 在上面的例子中, l_pet被写入了一次,如果是/ l_pet ,我将被写入N次。

An inspect statement allows for checking if an expression has a specific value, and can be applied to expressions of integral types (such as INTEGER_64 , CHARACTER_32 or NATURAL_8 ): inspect语句允许检查表达式是否具有特定值,并且可以应用于整数类型的表达式(例如INTEGER_64CHARACTER_32NATURAL_8 ):

inspect age
when 6 .. 16 then ...
when 18 then ...
when 80, 90 then ...
...
end

For discriminating over object types, conditional instructions are used: 为了区分对象类型,使用条件指令:

if attached {DOG} pet as dog then
   dog.eat (meat)
elseif attached {FISH} pet as fish then
   fish.eat (plants)
else
   io.put_string ("Strange animal how do I feed him???")
end

In a multi-branch instruction 在多分支指令中

inspect exp when ... then ... else ... end

The exp expression needs to be a character or an integer expression. exp表达式必须是字符或整数表达式。

In your given example I don't see the need to do that Object-Test , but if you need to do something like that you need to use the conditional instruction. 在您给出的示例中,我看不到需要执行Object-Test ,但是如果您需要执行类似的操作,则需要使用条件指令。

if ... then ... elseif ... then ... else ... end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM