【发布时间】:2017-01-07 15:15:27
【问题描述】:
我想要实现的就像虚拟代码一样:
type
CommandSetOne = (Command1, Command2, Command3);
CommandSetTwo = (Command4, Command5, Command6);
TRobot = class
procedure RegisterCommands(anyEnumerationType : TRttiEnumerationType);
procedure ExecuteCommands(anEnumeration : theEnumerationType);
end;
我可能有多个命令集,命令集中的任何命令都是可替换的。
TRobot有一个过程可以带一个枚举类型作为参数,他会保存这个类型,在ExecuteCommands过程中使用这个类型。
关于将任何枚举类型作为参数传递,我发现了一种方法是使用 TRttiEnumerationType,在调用端它应该如下所示:
var
rttiContext : TRttiContext;
typeref : TRttiType;
RobotA : TRobot;
begin
rttiContext := TRttiContext.Create();
RobotA := TRobot.Create();
RobotA.RegisterCommands(rttiContext.GetType(TypeInfo(CommandSetOne)));
end;
但我在传递像 Command1 这样的命令时遇到了困难。我已经为 theEnumerationType 尝试了 Variant,但似乎我无法将 Command1 传递给它。
我知道我是否使用 TStringList 之类的东西,因为这是一种更简单的方法来做我想做的事,但我希望在编译时由 delphi 检查,以防我错误输入某些命令(使用 TstringList 我可以添加代码在运行时检查)
所以真正的问题是:
我应该为 EnumerationType 使用哪种类型?
如果无法做到这一点,还有其他使用枚举的解决方案吗?
或者任何解决方案都可以提供合规时间检查以及灵活的结构?
编辑:
感谢 David 的建议,我应该同时使用 Rtti 的东西,所以为了清楚起见,我添加了 RegisterCommands 的实现
implementation
procedure TRobot.RegisterCommands(anyEnumerationType : TRttiEnumerationType);
begin
theEnumerationType := anyEnumerationType;
end;
procedure TRobot.ExecuteCommands (anyEnumerationValueoftheType : ???);
begin
//do something with the command
end;
那么什么应该适合该类型的任何枚举值?
例如,如果我在 RegisterCommands 中使用 CommandSetOne, delphi如何接受Command1或Command2或Command3?
更具体地说,delphi 是否可以仅为 Command1 或 Command2 或 Command3 限制房间?意思是如果我放 Command4 它会给我一个编译错误?
【问题讨论】:
-
你为什么要使用 RTTI?这听起来像是泛型的工作。
-
什么是
theEnumerationType? -
@DavidHeffernan theEnumerationType 是 CommandSetOne 或 CommandSetTwo 或我注册到 Trobot 的任何枚举类型
-
@RemyLebeau 这是一种泛型,因为发送到 RegisterCommands 的类型可能会改变
-
你可以查看这个链接,stackoverflow.com/questions/11110704/…
标签: delphi