我正在将一些C#代码转换为Delphi。
在c#中,我有Nullabe类型:
System.Nullable<T> variable
或
T? variable
然后,我可以使用以下内容:
int?[] arr = new int?[10];
是否有一些与之相当的Delphi VCL?
答案 0 :(得分:1)
unit Nullable;
{$mode delphi}{$H+}
interface
uses
Classes, SysUtils;
type
TNullable<T> = record
private
FHasValue: Boolean;
FValue: T;
function GetValue: T;
procedure SetValue(AValue: T);
public
procedure Clear;
property HasValue: Boolean read FHasValue;
property Value: T read GetValue write SetValue;
class operator Implicit(A: T): TNullable<T>;
class operator Implicit(A: Pointer): TNullable<T>;
end;
implementation
{ TNullable }
function TNullable<T>.GetValue: T;
begin
if FHasValue then
Result := FValue
else
raise Exception.Create('Variable has no value');
end;
procedure TNullable<T>.SetValue(AValue: T);
begin
FValue := AValue;
FHasValue := True;
end;
procedure TNullable<T>.Clear;
begin
FHasValue := False;
end;
class operator TNullable<T>.Implicit(A: T): TNullable<T>;
begin
Result.Value := A;
end;
class operator TNullable<T>.Implicit(A: Pointer): TNullable<T>;
begin
if A = nil then Result.Clear
else raise Exception.Create('Pointer value not allowed');
end;
end.
答案 1 :(得分:0)
我已经为Delphi 2007实现了可为空的解决方案,但它与较高版本完全兼容。
下载地址:https://drive.google.com/open?id=1KlvVPkxil80xvTLhCV4t9VUtkUbHvdJ7