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的相同的功能的最佳方式? 请注意,一个对象可能是我测试的几个类的后代。
太棒了!这正是我需要的。只是好奇:在使用宏进行编译期间是否可以实现相同的结果?由于对象的类型是编译时已知的。我正在测试的课程数量是不变的。 – montonero
我不确定你想在这里使用宏来达到什么目的。生成'add()'方法和'_initializeSystems' /'_executeSystems'列表? – Gama11
该函数(Systems.add(system:ISystem))的逻辑如下:取决于'system'是否是可能的ISystemXyz类的后代(有限数量) - 将其添加到相应的容器中。如果'system'是多个ISystemXyz的子类,它会被添加到多个容器中。 当我调用'systems.add(mySystem)'时,我知道编译期间mySystem的类型,因此希望能够确定在编译和内联函数期间将'mySystem'添加到哪里,因此在运行时没有ifs。虽然'Std.is'(如果我理解正确的话)在运行时会这样做。 – montonero