也许(可能)这是一个愚蠢的问题,但我找不到答案……
请检查这个假设代码:
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;
解决方法
枚举类型不能为零.它必须采用其中一个已定义的枚举值.
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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。