Delphi在函数中指定泛型值
由于Delphi(很遗憾)不支持nullable类型,我想尝试自己实现它们。这是我到目前为止写的:Delphi在函数中指定泛型值,delphi,generics,Delphi,Generics,由于Delphi(很遗憾)不支持nullable类型,我想尝试自己实现它们。这是我到目前为止写的: unit Nullable; interface uses System.SysUtils, Generics.Collections; type Nullable<T> = class private FValue: T; FHasValue: boolean; function getValue: T; procedure setValue(c
unit Nullable;
interface
uses
System.SysUtils, Generics.Collections;
type
Nullable<T> = class
private
FValue: T;
FHasValue: boolean;
function getValue: T;
procedure setValue(const val: T);
public
constructor Create(value: T);
procedure setNull;
property value: T read getValue write setValue;
property hasValue: boolean read FHasValue;
end;
implementation
{ Nullable<T> }
constructor Nullable<T>.Create(value: T);
begin
Fvalue := value;
FHasValue := true;
end;
procedure Nullable<T>.setNull;
begin
FHasValue := false;
end;
procedure Nullable<T>.setValue(const val: T);
begin
FHasValue := true;
FValue := T; //COMPILER ERROR HERE
end;
function Nullable<T>.getValue: T;
begin
if (FHasValue = false) then
raise Exception.Create('There is not a value!');
Result := T;
end;
end.
而不是
FValue := T;
你是说
FValue := val;
您在setter方法中也犯了同样的错误,该方法以一种全新的方式进行了修复
Result := T;
与
请记住,T
是一种类型
现在已经有很多好的可空类型实现,例如Spring有一个。您可能会从中获得灵感,甚至可以按原样使用。您知道他们是否计划实现nullables吗?可能是Delphi10.3或Delphi11或其他版本。不太确定,但我想它对于像C这样的本机实现是有用的#
Result := T;
Result := FValue;