将枚举类型变量设置为nil

5
也许(很可能)这是一个愚蠢的问题,但我没有找到答案...
请检查这个假想的代码:
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设置为这个自定义类型的变量,以便我可以检查函数结果并避免问题?

1个回答

5

枚举类型不可以为 nil,它必须取其中一个已定义的枚举值。

你有几个选项。你可以添加另一个枚举类型:

type
  TCustomType = (NoValue, Type1, Type2, 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;

我正在使用Delphi 7,所以我认为异常的想法很棒!谢谢! - Guybrush
3
或者调用GetEnumValue,如果返回-1,则引发异常。 - TLama
1
@Paruba 我个人认为异常应该是非常罕见的情况,因此除非你百分之百确定输入始终正确,否则最好避免使用异常模式。但对于几乎致命的用例,应该中止整个执行过程,并断开客户端连接等操作。 - Arnaud Bouchez
@ArnaudBouchez,你说得对,我使用了“TryXXX”的方式...谢谢! - Guybrush
1
太好了!谢谢TLama! - Guybrush
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接