[英]Setting an enumerated type var to nil
Maybe (probably) it is a silly question, but I didn't find an answer... 也许(可能)这是一个愚蠢的问题,但我找不到答案......
Please, check this hypothetical code: 请检查这个假设代码:
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;
Please, how can I set nil / null / empty to this custom type var, so I can check the function result and avoid problems? 请问,如何将nil / null / empty设置为此自定义类型var,以便检查函数结果并避免出现问题?
An enumerated type cannot be nil
. 枚举类型不能nil
。 It must take one of the defined enumeration values. 它必须采用其中一个已定义的枚举值。
You have a few options. 你有几个选择。 You can add another enum: 您可以添加另一个枚举:
type
TCustomType = (NoValue, Type1, Type2, Type3);
You can use a nullable type. 您可以使用可空类型。 For instance Spring has Nullable<T>
. 例如,Spring有Nullable<T>
。
You could raise an exception if no value could be found. 如果找不到任何值,您可以引发异常。
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;
Or you can use the TryXXX
pattern. 或者您可以使用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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.