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

delphi – 将枚举类型var设置为nil

发布时间:2020-12-15 09:23:14 所属栏目:大数据 来源:网络整理
导读:也许(可能)这是一个愚蠢的问题,但我找不到答案…… 请检查这个假设代码: type TCustomType = (Type1,Type2,Type3);function CustomTypeToStr(CTp: TCustomType): string;begin Result := ''; case CTp of Type1: Result := 'Type1'; Type2: Result := 'Type
也许(可能)这是一个愚蠢的问题,但我找不到答案……

请检查这个假设代码:

type
  TCustomType = (Type1,Type2,Type3);

function CustomTypeToStr(CTp: TCustomType): string;
begin
  Result := '';
  case CTp of
    Type1: Result := 'Type1';
    Type2: Result := 'Type2';
    Type3: Result := 'Type3';
  end;
end;

function StrToCustomType(Str: string): TCustomType;
begin
  Result := nil;           <--- ERROR (Incompatible types: 'TCustomType' and 'Pointer')
  if (Str = 'Type1') then
    Result := Type1 else
  if (Str = 'Type2') then
    Result := Type2 else
  if (Str = 'Type3') then
    Result := Type3;
end;

请问,如何将nil / null / empty设置为此自定义类型var,以便检查函数结果并避免出现问题?

解决方法

枚举类型不能为零.它必须采用其中一个已定义的枚举值.

你有几个选择.您可以添加另一个枚举:

type
  TCustomType = (NoValue,Type1,Type3);

您可以使用可空类型.例如,Spring有Nullable< T>.

如果找不到任何值,您可以引发异常.

function StrToCustomType(Str: string): TCustomType;
begin
  if (Str = 'Type1') then
    Result := Type1 
  else if (Str = 'Type2') then
    Result := Type2 
  else if (Str = 'Type3') then
    Result := Type3
  else
    raise EMyException.Create(...);
end;

或者您可以使用TryXXX模式.

function TryStrToCustomType(Str: string; out Value: TCustomType): Boolean;
begin
  Result := True;
  if (Str = 'Type1') then
    Value := Type1 
  else if (Str = 'Type2') then
    Value := Type2 
  else if (Str = 'Type3') then
    Value := Type3
  else
    Result := False;
end;

function StrToCustomType(Str: string): TCustomType;
begin
  if not TryStrToCustomType(Str,Result) then
    raise EMyException.Create(...);
end;

(编辑:李大同)

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

    推荐文章
      热点阅读