[英]Eiffel: How do I compare the type of an object to a given type?
如何将对象的类型与给定类型(Java中的instanceOf语句)进行比较?
do_stuff (a_type: TYPE)
local
an_object: ANY
do
an_object := get_from_sky
if an_object.instanceOf (a_type) then
io.putstring("Object is same type as parameter")
else
io.putstring("Object is NOT same type as parameter")
end
end
根据解决方案的一般性,有不同的选择。 首先,考虑总是附加an_object
的情况:
a_type
始终表示引用类型。
对于引用类型,可以使用TYPE
类attempted
的功能(带有别名/
)。
if attached (a_type / an_object) then -- Conforms. else -- Does not conform. end
a_type
可以表示引用类型或扩展类型。
在这种情况下, attempted
使用TYPE
类的功能是不可用的,因为它将始终为扩展类型返回附加的对象。 因此,应直接比较类型。
if an_object.generating_type.conforms_to (({REFLECTOR}.type_of_type ({REFLECTOR}.detachable_type (a_type.type_id)))) then -- Conforms. else -- Does not conform. end
如果an_object
也可以是Void
,那么该条件应进行其他Void
测试。 用C
表示上述情况的条件,处理可拆卸an_object
的测试将是:
if
-- If an_object is attached.
attached an_object and then C or else
-- If an_object is Void.
not attached an_object and then not a_type.is_attached
then
-- Conforms.
else
-- Does not conform.
end
如果您想检查的类型a_type
是相同的类型an_object
,使用该功能{ANY}.same_type
,如果你想查询类型一致性只使用{ANY}.conforms_to
do_stuff (a_type: TYPE)
local
an_object: ANY
do
an_object := get_from_sky
if an_object.same_type (a_type) then
io.putstring("Object an_object is same type as argment a_type")
elseif an_object.conforms_to (a_type)
io.putstring("Object an_object conforms to type of a_type ")
else
io.putstring ("...")
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.