Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Delphi在函数中指定泛型值_Delphi_Generics - Fatal编程技术网

Delphi在函数中指定泛型值

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

由于Delphi(很遗憾)不支持nullable类型,我想尝试自己实现它们。这是我到目前为止写的:

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;