2017-06-29 106 views
2

我希望能夠檢查一個對象是否是給定類的後代,但似乎不可能。如何檢查一個對象是否是haxe中給定類的後代?

E.g.我想從端口C#

public virtual Systems Add(ISystem system) { 
     var initializeSystem = system as IInitializeSystem; 
     if(initializeSystem != null) { 
      _initializeSystems.Add(initializeSystem); 
     } 

     var executeSystem = system as IExecuteSystem; 
     if(executeSystem != null) { 
      _executeSystems.Add(executeSystem); 
     } 

     var cleanupSystem = system as ICleanupSystem; 
     if(cleanupSystem != null) { 
      _cleanupSystems.Add(cleanupSystem); 
     } 

     var tearDownSystem = system as ITearDownSystem; 
     if(tearDownSystem != null) { 
      _tearDownSystems.Add(tearDownSystem); 
     } 

     return this; 
    } 

下面的代碼即使C++允許這樣的:

using std::dynamic_pointer_cast; 
auto SystemContainer::add(std::shared_ptr<ISystem> system) -> SystemContainer* 
{ 
    { 
     if (auto systemInitialize = dynamic_pointer_cast<IInitializeSystem>(system)) { 
      initializeSystems_.emplace_back(systemInitialize); 
     } 
     if (auto cleanupSystem = dynamic_pointer_cast<ICleanupSystem>(system)) { 
      cleanupSystems_.emplace_back(cleanupSystem); 
     } 
     if (auto teardownSystem = dynamic_pointer_cast<ITearDownSystem>(system)) { 
      teardownSystems_.emplace_back(teardownSystem); 
     } 
    } 

    if (auto systemExecute = dynamic_pointer_cast<IExecuteSystem>(system)) { 
     executeSystems_.emplace_back(systemExecute); 
    } 

    return this; 
} 

什麼是實現haXe的相同的功能的最佳方式? 請注意,一個對象可能是我測試的幾個類的後代。

回答

3

你試過Std.is()

if (Std.is(system, IInitializeSystem)) { 
    _initializeSystems.add(cast system); 
} 

if (Std.is(system, IExecuteSystem)) { 
    _executeSystems.add(cast system); 
} 

// etc 
+0

太棒了!這正是我需要的。只是好奇:在使用宏進行編譯期間是否可以實現相同的結果?由於對象的類型是編譯時已知的。我正在測試的課程數量是不變的。 – montonero

+0

我不確定你想在這裏使用宏來達到什麼目的。生成'add()'方法和'_initializeSystems' /'_executeSystems'列表? – Gama11

+0

該函數(Systems.add(system:ISystem))的邏輯如下:取決於'system'是否是可能的ISystemXyz類的後代(有限數量) - 將其添加到相應的容器中。如果'system'是多個ISystemXyz的子類,它會被添加到多個容器中。 當我調用'systems.add(mySystem)'時,我知道編譯期間mySystem的類型,因此希望能夠確定在編譯和內聯函數期間將'mySystem'添加到哪裏,因此在運行時沒有ifs。雖然'Std.is'(如果我理解正確的話)在運行時會這樣做。 – montonero

相關問題