我已经创建了一个像这样的可空类型,这是我在 SO 答案中发现的,不记得是哪一个了。
unit NullableType;
interface
uses
System.SysUtils, System.Rtti;
type
TNullable<T> = record
private
FValue: T;
FHasValue: IInterface;
function GetHasValue: Boolean;
function GetValue: T;
procedure SetValue(const AValue: T);
public
constructor Create(AValue: T);
function ToString: string; // <-- add this for easier use!
property HasValue: Boolean read GetHasValue;
property Value: T read GetValue write SetValue;
end;
implementation
constructor TNullable<T>.Create(AValue: T);
begin
SetValue(AValue);
end;
function TNullable<T>.GetHasValue: Boolean;
begin
Result := FHasValue <> nil;
end;
function TNullable<T>.GetValue: T;
begin
if HasValue then
Result := FValue
else
Result := Default(T);
end;
procedure TNullable<T>.SetValue(const AValue: T);
begin
FValue := AValue;
FHasValue := TInterfacedObject.Create;
end;
function TNullable<T>.ToString: string;
begin
if HasValue then
begin
if TypeInfo(T) = TypeInfo(TDateTime) then
Result := DateTimeToStr(PDateTime(@FValue)^)
else if TypeInfo(T) = TypeInfo(TDate) then
Result := DateToStr(PDateTime(@FValue)^)
else if TypeInfo(T) = TypeInfo(TTime) then
Result := TimeToStr(PDateTime(@FValue)^)
else
Result := TValue.From<T>(FValue).ToString;
end
else
Result := 'null';
end;
end.
我的问题是我不知道如何将其设置为空。
例如
var
id : TNullable<integer>;
begin
if Edit1.Text <> '' then
id.Value := StrToInt(Edit1.Text)
else
id.Value := null; // runtime error
这给了我运行时错误
无法将类型 (Null) 的变量转换为类型 (Integer)
我已经有一段时间没有用 Delphi 编程了,我就是搞不清楚如何设置id
变量的值null
id.Value := nil;
给出编译器错误
不兼容的类型:“整数”和“指针”
只有不设置 的值,id
我才能获得它的值null
,但如果我想将其设置为任何值,包括 null ,该怎么办?怎么做?