本文介绍了我可以定义只能包含这些值的MyType吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个问题:如果我有这样的值:'AA','AB','AC','BC' - 我可以定义只能包含这些值的MyType吗?我想在模式下做:
键入MyType = ...; // something
var X:MyType;
begin
x:='AA'; //有效,'AA'包含在X
X:='SS'中; //无效,SS不包括在X中,而不是引发异常。
结束
我该如何解决?是否有一些解决方案直接使用类型数据?
解决方案
这实际上是相当简单的使用运算符重载。
做
键入
TMyType = record
private
键入
TMyTypeEnum =(mtAA,mtAB,mtAC,mtBC);
var
FMyTypeEnum:TMyTypeEnum;
public
class operator Implicit(const S:string):TMyType;
class operator Implicit(const S:TMyType):string;
结束
实现
类运算符TMyType.Implicit(const S:string):TMyType;
begin
如果SameStr(S,'AA')然后开始result.FMyTypeEnum:= mtAA;出口;结束;
如果SameStr(S,'AB')然后开始result.FMyTypeEnum:= mtAB;出口;结束;
如果SameStr(S,'AC')然后开始result.FMyTypeEnum:= mtAC;出口;结束;
如果SameStr(S,'BC')然后开始result.FMyTypeEnum:= mtBC;出口;结束;
raise Exception.CreateFmt('Invalid value%s。',[S]);
结束
类运算符TMyType.Implicit(const S:TMyType):string;
begin
case S.FMyTypeEnum
mtAA:result:='AA';
mtAB:result:='AB';
mtAC:result:='AC';
mtBC:result:='BC';
结束
结束
现在你可以做
procedure TForm1.Button1Click(Sender:TObject);
var
S:TMyType;
begin
S:='AA'; // works
Self.Caption:= S;
S:='DA'; //不起作用,异常生成
Self.Caption:= S;
结束
I have this problem: if I have, for example, these values: 'AA', 'AB', 'AC', 'BC' - can I define MyType that can contain only these values?
I want to do in mode that:
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;
How can I solve it? Is there some solution directly using type data?
解决方案
This is actually rather simple using operator overloading.
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;
Now you can do
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;
这篇关于我可以定义只能包含这些值的MyType吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!