在 Delphi XE2 中,我尝试重载记录上的 in
运算符,以允许我检查记录表示的值是否是集合的一部分。我的代码如下所示:
type
MyEnum = (value1, value2, value3);
MySet = set of MyEnum;
MyRecord = record
Value: MyEnum;
class operator In(const A: MyRecord; B: MySet): Boolean;
end;
class operator MyRecord.In(const A: MyRecord; B: MySet): Boolean;
begin
Result := A.Value in B;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
R: MyRecord;
S: MySet;
begin
R.Value := value1;
S := [value1, value2];
Button1.Caption := BoolToStr(R in S);
end;
代码无法编译。对于语句R in S
,编译器会说:不兼容的类型MyRecord
和MyEnum
。
如何重载 MyRecord
上的 In
运算符,以便 R in S
的计算结果为 True
上面的代码?
最佳答案
要使 in 运算符起作用,正确的操作数必须是记录类型,因为它是集合运算符而不是二元运算符。在您的情况下,它是左操作数。
因此以下内容将起作用:
type
MyRecord = record
Value: MyEnum;
class operator In(const A: MyRecord; const B: MySet): Boolean;
end;
MyRecord2 = record
Value: MySet;
class operator In(const A: MyRecord; const B: MyRecord2): Boolean;
class operator In(const A: MyEnum; const B: MyRecord2): Boolean;
end;
class operator MyRecord.In(const A: MyRecord; const B: MySet): Boolean;
begin
Result := A.Value in B;
end;
class operator MyRecord2.In(const A: MyRecord; const B: MyRecord2): Boolean;
begin
Result := A.Value in B.Value;
end;
class operator MyRecord2.In(const A: MyEnum; const B: MyRecord2): Boolean;
begin
Result := A in B.Value;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
R: MyRecord;
R2: MyRecord2;
begin
R.Value := value1;
R2.Value := [value1, value2];
if R in R2 then;
if value1 in R2 then;
end;
关于Delphi 'in' 集合上的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8045635/