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

Eiffel:在运行时创建类型化对象

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

    尝试创建一个由@runtime决定的对象时,我遇到了类似的情况:

    class ZOO
    
    feature
    
        animals: LINKED_LIST[ANIMAL]
    
        default_create
            do
                create animals.make
                animals.extend(create {LION})
                animals.extend(create {SERPENT})
                animals.extend(create {BIRD})
            end
    
        open
            local
                l_sector: ZOO_SECTOR[ANIMAL]
            do
                across
                    animals as animal
                loop
                    create {ZOO_SECTOR[animal.item.generating_type]} l_sector
                end
            end
    

    create {ZOO_SECTOR[animal.item.generating_type]} l_sector 编译器不同意我的意见,我试过了 l_type: TYPE[ANIMAL] create {ZOO_SECTOR[l_type]} l_sector

    open
        local
            l_sector: ZOO_SECTOR[ANIMAL]
        do
            across
                animals as animal
            loop
                if attached {LION} animal.item then
                    create {ZOO_SECTOR[LION]} l_sector
                else if attached {SERPENT} animal.item then
                    create {ZOO_SECTOR[SERPENT]} l_sector
                else
                    .....
            end
        end
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Alexander Kogtenkov    7 年前

    Eiffel类型系统依赖于类结构,类结构在编译时是固定的。可以动态地添加类型(例如,应该可以使用反射提出解决方案),但这不能直接用语言本身来表达。

    ZOO_SECTOR 类型可以直接在动物类中编码:

    class ANIMAL feature ...
        sector: ZOO_SECTOR [like Current] do create Result end
    end
    

    由于使用 like Current ,不需要在子体中添加任何新代码。示例中的循环将变成

    across
        animals as animal
    loop
        l_sector := animal.item.sector
    end
    

    ZOO_SECTOR [LION] 对于类型为的项 LION 等等。