简体   繁体   English

埃菲尔:如何比较对象的类型和给定的类型?

[英]Eiffel: How do I compare the type of an object to a given type?

How do I compare the type of an object to a given type (instanceOf statement in Java)? 如何将对象的类型与给定类型(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

Depending on the generality of the solution, there are different options. 根据解决方案的一般性,有不同的选择。 First, consider the case when an_object is always attached: 首先,考虑总是附加an_object的情况:

  1. a_type always denotes a reference type. a_type始终表示引用类型。

    For reference types one can use the feature attempted (with an alias / ) of the class TYPE . 对于引用类型,可以使用TYPEattempted的功能(带有别名/ )。

     if attached (a_type / an_object) then -- Conforms. else -- Does not conform. end 
  2. a_type can denote either a reference or expanded type. a_type可以表示引用类型或扩展类型。

    The feature attempted of the class TYPE is unusable in this case because it would always return an attached object for expanded types. 在这种情况下, attempted使用TYPE类的功能是不可用的,因为它将始终为扩展类型返回附加的对象。 Therefore, the types should be compared directly. 因此,应直接比较类型。

     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 

If an_object could also be Void , the condition should have additional tests for voidness. 如果an_object也可以是Void ,那么该条件应进行其他Void测试。 Denoting the conditions from the cases above with C , the tests that handle detachable an_object would be: 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

If you want to check if the type of a_type is identical to the type of an_object , use the feature {ANY}.same_type , if you want to check type conformance just use {ANY}.conforms_to 如果您想检查的类型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.

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