我有这个问题:例如,如果我有这些值:'AA'、'AB'、'AC'、'BC' - 我可以定义仅包含这些值的 MyType 吗?
我想在模式下做:
type MyType = ... ; // something
var X: MyType;
begin
x := 'AA' ; // is valid, 'AA' is included in X
X := 'SS' ; // not valid, 'SS' not is included in X, than raise an exception.
end;
我该如何解决?有没有直接使用类型数据的解决方案?
使用运算符重载实际上相当简单。
Do
type
TMyType = record
private
type
TMyTypeEnum = (mtAA, mtAB, mtAC, mtBC);
var
FMyTypeEnum: TMyTypeEnum;
public
class operator Implicit(const S: string): TMyType;
class operator Implicit(const S: TMyType): string;
end;
implementation
class operator TMyType.Implicit(const S: string): TMyType;
begin
if SameStr(S, 'AA') then begin result.FMyTypeEnum := mtAA; Exit; end;
if SameStr(S, 'AB') then begin result.FMyTypeEnum := mtAB; Exit; end;
if SameStr(S, 'AC') then begin result.FMyTypeEnum := mtAC; Exit; end;
if SameStr(S, 'BC') then begin result.FMyTypeEnum := mtBC; Exit; end;
raise Exception.CreateFmt('Invalid value "%s".', [S]);
end;
class operator TMyType.Implicit(const S: TMyType): string;
begin
case S.FMyTypeEnum of
mtAA: result := 'AA';
mtAB: result := 'AB';
mtAC: result := 'AC';
mtBC: result := 'BC';
end;
end;
现在你可以做
procedure TForm1.Button1Click(Sender: TObject);
var
S: TMyType;
begin
S := 'AA'; // works
Self.Caption := S;
S := 'DA'; // does not work, exception raised
Self.Caption := S;
end;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)