将枚举类型var设置为nil

Guy*_*ush 4 delphi

也许(可能)这是一个愚蠢的问题,但我找不到答案......

请检查这个假设代码:

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;
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*nan 5

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

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

type
  TCustomType = (NoValue, Type1, Type2, Type3);
Run Code Online (Sandbox Code Playgroud)

您可以使用可空类型.比如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;
Run Code Online (Sandbox Code Playgroud)

或者您可以使用该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;
Run Code Online (Sandbox Code Playgroud)

  • 或者调用`GetEnumValue`,如果返回-1,则引发异常. (2认同)