我会以不同的方式实现 Delphi 端(见下文),但除此之外,您的解决方案似乎是正确的。
正如您正确观察到的那样,怪癖是 DWScript 将静态集表示为数组。但是请注意,这只是编译器前端的一个限制,希望有一天会得到解决。请参阅DWScript 问题 #10:改进从静态数组到集合的隐式转换。
以下脚本演示了在哪些情况下编译器会在集合和数组之间执行隐式转换:
type
TMyEnum = (meOne, meTwo);
type
TMySet = set of TMyEnum;
type
TMyArray = array of TMyEnum;
procedure TestSet(MySet: TMySet);
begin
ShowMessage(integer(MySet).toString);
end;
procedure TestArray(MyArray: TMyArray);
var
MySet: TMySet;
begin
MySet := [];
for var i := 0 to MyArray.Length-1 do
Include(MySet, MyArray[i]);
ShowMessage(integer(MySet).toString);
end;
begin
TestSet([]);
TestArray([]);
TestSet([meOne]);
TestArray([meOne]);
TestSet([meOne, meTwo]);
TestArray([meOne, meTwo]);
var VarSet: TMySet = [meOne, meTwo];
TestSet(VarSet);
// Syntax Error: Argument 0 expects type "array of TMyEnum" instead of "TMySet"
// TestArray(VarSet);
var VarArray: TMyArray = [meOne, meTwo];
TestArray(VarArray);
// Syntax Error: Argument 0 expects type "array of TMyEnum" instead of "TMySet"
// TestArray(VarSet);
// Syntax Error: Incompatible types: "TMySet" and "array [0..1] of TMyEnum" const ConstSet: TMySet = [meOne, meTwo];
// const ConstSet: TMySet = [meOne, meTwo];
// TestSet(ConstSet);
// TestArray(ConstSet);
// Syntax Error: Incompatible types: "array of TMyEnum" and "array [0..1] of TMyEnum"
// const ConstArray: TMyArray = [meOne, meTwo];
// TestSet(ConstArray);
// TestArray(ConstArray);
end;
以上纯属脚本端实现。当您将 Delphi 端实现添加到混合中时,它可能会出现问题。
考虑一个简化的MessageDlg
函数实现:
Delphi 端声明(通过 TdwsUnit):
type
TMsgDlgBtn = (mbYes, mbNo, mbOK, mbCancel, etc...);
TMsgDlgButtons = set of TMsgDlgBtn;
function MessageDlg(const Msg: string; Buttons: TMsgDlgButtons): integer;
Delphi端实现:
Info.ResultAsInteger := MessageDlg(Info.ParamAsString[0], mtInformation, TMsgDlgButtons(Word(Info.ParamAsInteger[1])), -1);
脚本端使用:
begin
// Implicit cast from array to set fails:
// Syntax Error: There is no overloaded version of "MessageDlg" that can be called with these arguments
// MessageDlg('Test', [mbOK]);
var Buttons: TMsgDlgButtons = [mbOK];
MessageDlg('Test', Buttons);
end;
现在让我们尝试使用您的解决方案将 set 参数声明为数组来代替:
Delphi 端声明(通过 TdwsUnit):
type
TMsgDlgBtn = (mbYes, mbNo, mbOK, mbCancel, etc...);
TMsgDlgButtons = array of TMsgDlgBtn;
function MessageDlg(const Msg: string; Buttons: TMsgDlgButtons): integer;
Delphi端实现:
var
Buttons: TMsgDlgButtons;
i: integer;
ButtonArray: IScriptDynArray;
begin
ButtonArray := Info.Params[1].ScriptDynArray;
Buttons := [];
for i := 0 to ButtonArray.ArrayLength-1 do
Include(Buttons, TMsgDlgBtn(ButtonArray.AsInteger[i]));
Info.ResultAsInteger := MessageDlgEx(Info.ParamAsString[0], mtInformation, Buttons, -1);
end;
脚本端使用:
begin
MessageDlg('Test', [mbOK]);
var Buttons: TMsgDlgButtons = [mbOK];
// Note that an implicit cast from set to array is performed
MessageDlg('Test', Buttons);
end;
在我自己的 DWScript 分支中,我修改了编译器以执行从枚举值数组到集合的隐式转换:DWScript pull request #4: Enhancement to set type。这很好地工作并解决了上述所有否则失败的情况。