Eiffel:如何将对象的类型与给定类型进行比较?
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
始终表示引用类型。
对于引用类型,可以使用 class TYPE
.
的特性 attempted
(别名 /
)
if attached (a_type / an_object) then
-- Conforms.
else
-- Does not conform.
end
a_type
可以表示引用类型或扩展类型。
class TYPE
的功能 attempted
在这种情况下不可用,因为它总是 return 扩展类型的附加对象。因此,应该直接比较类型。
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
,条件应该有额外的无效性测试。用 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
如何将对象的类型与给定类型(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
始终表示引用类型。对于引用类型,可以使用 class
的特性TYPE
.attempted
(别名/
)if attached (a_type / an_object) then -- Conforms. else -- Does not conform. end
a_type
可以表示引用类型或扩展类型。class
TYPE
的功能attempted
在这种情况下不可用,因为它总是 return 扩展类型的附加对象。因此,应该直接比较类型。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
,条件应该有额外的无效性测试。用 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