Delphi在函数中分配通用值

Raf*_*ssi 2 delphi generics

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

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.
Run Code Online (Sandbox Code Playgroud)

似乎我无法FValue使用函数中的通用值进行分配.有没有办法做到这一点?

我想要轻松实现nullables.我需要一个setValue函数,因为我需要将其赋值FHasValue为true或false(所以我知道该值是否为"可空").在主窗体中我会调用这样的代码:

var a: Nullable<integer>;
begin

 a := Nullable<integer>.Create(5);
 try

  a.setNull;

  if (not a.hasValue) then
   memo1.lines.add('nullo')
  else
   memo1.lines.add('valore = ' + a.value.toString);

 finally
  a.Free;
 end;
Run Code Online (Sandbox Code Playgroud)

Dav*_*nan 5

代替

FValue := T;
Run Code Online (Sandbox Code Playgroud)

你的意思是

FValue := val;
Run Code Online (Sandbox Code Playgroud)

你在setter方法中犯了同样的错误,这种错误以类似的方式被修复

Result := T;
Run Code Online (Sandbox Code Playgroud)

Result := FValue;
Run Code Online (Sandbox Code Playgroud)

请记住,这T是一种类型.

已经存在许多可以为空的类型的良好实现,例如Spring有一个.你可以从这些中汲取灵感,甚至可以按原样使用.

  • 它在路线图上,所以它应该到达某个点. (2认同)