代码之家  ›  专栏  ›  技术社区  ›  Pipo

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

  •  0
  • Pipo  · 技术社区  · 6 年前

    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
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Alexander Kogtenkov    6 年前

    根据解决方案的通用性,有不同的选项。首先,考虑当时的情况 an_object 始终附加:

    1. a_type 总是表示引用类型。

      attempted (化名为 / )全班同学 TYPE

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

      特色 全班同学 在这种情况下是不可用的,因为它将始终返回扩展类型的附加对象。因此,应直接比较这些类型。

      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
      

    对象 也可能是 Void ,该条件应进行额外的空隙率测试。表示上述情况的条件 C ,处理可拆卸的 可能是:

    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
    
        2
  •  -1
  •   javierv    6 年前

    如果要检查 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