有没有办法在没有任何附加实例的情况下测试类的给定泛型参数?
class BAG[G -> MOUSE]
feature --
discriminate
do
if G.conforms_to (MAMMAL) then
io.putstring ("you gave me a real animal")
elseif G.conforms_to (COMPUTER_ACCESSORY) then
io.putstring ("Seems you don't like animals such as computers")
else
io.pustring ("Still dont know what you are dealing with")
end
end
答案 0 :(得分:2)
您几乎钉牢了它。缺少的部分是花括号和括号:
if ({G}).conforms_to ({MAMMAL}) then
io.put_string ("You gave me a real animal.")
elseif ({G}).conforms_to ({COMPUTER_ACCESSORY}) then
io.put_string ("Seems you don't like animals such as computers.")
else
io.put_string ("Still don't know what you are dealing with.")
end
说明:
{FOO}
,其中FOO
是类型名称,代表类型对象。它适用于任何类型,包括形式泛型,因此{G}
和{MAMMAL}
。{FOO}.bar
保留用于非对象调用。但是这里我们要对类型对象进行对象调用。因此,{G}
用括号括起来:({G}).conforms_to
(而不是{G}.conforms_to
)。