简体   繁体   中英

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)?

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:

  1. a_type always denotes a reference type.

    For reference types one can use the feature attempted (with an alias / ) of the class TYPE .

     if attached (a_type / an_object) then -- Conforms. else -- Does not conform. end 
  2. a_type can denote either a reference or expanded type.

    The feature attempted of the class TYPE is unusable in this case because it would always return an attached object for expanded types. 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. Denoting the conditions from the cases above with C , the tests that handle detachable an_object would be:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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