簡體   English   中英

埃菲爾:如何比較對象的類型和給定的類型?

[英]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的情況:

  1. a_type始終表示引用類型。

    對於引用類型,可以使用TYPEattempted的功能(帶有別名/ )。

     if attached (a_type / an_object) then -- Conforms. else -- Does not conform. end 
  2. 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM