加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 我可以定义只包含这些值的MyType吗?

发布时间:2020-12-15 09:40:02 所属栏目:大数据 来源:网络整理
导读:我有这个问题:例如,如果我有这些值:’AA’,’AB’,’AC’,’BC’ – 我可以定义只包含这些值的MyType吗? 我想以这样的模式做: type MyType = ... ; // somethingvar X: MyType;begin x := 'AA' ; // is valid,'AA' is included in X X := 'SS' ; // not
我有这个问题:例如,如果我有这些值:’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;

我该如何解决?有没有直接使用类型数据的解决方案?

解决方法

使用运算符重载实际上相当简单.

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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读