由于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.
看来我无法使用从函数中获取的通用值来分配FValue
。有办法做到这一点吗?
我想要简单地实现可空值。我需要一个 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;
最佳答案
而不是
FValue := T;
你的意思是
FValue := val;
您在 setter 方法中犯了同样的错误,该方法已以类似的方式替换为固定的
Result := T;
与
Result := FValue;
请记住,T
是一种类型。
已经存在许多可空类型的良好实现,例如 Spring 就有一个。您可能会从中汲取灵感,甚至按原样使用其中一个。
关于Delphi在函数中分配通用值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44887070/