You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Delphi自定义TNullable<integer>类型设置为null?

问题根源

你的自定义TNullable<T>类型靠FHasValue接口变量是否为nil来标记"是否有值",但目前只提供了SetValue(标记为有值)的逻辑,缺少主动置空的方法——直接给Value属性赋值null或nil会报错,因为Value是具体的值类型(比如Integer),本身不支持空值,空状态是靠TNullable的内部标记实现的。


解决方案:给TNullable<T>添加置空逻辑

方法1:新增Clear方法(最直接)

在TNullable<T>的public区域添加置空方法,手动将FHasValue设为nil:

  1. 修改接口部分
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);
    procedure Clear; // 新增置空方法
    function ToString: string;
    property HasValue: Boolean read GetHasValue;
    property Value: T read GetValue write SetValue;
  end;
  1. 实现Clear方法
procedure TNullable<T>.Clear;
begin
  FHasValue := nil;
  // 可选:将FValue重置为类型默认值,不重置也不影响,因为HasValue为false时GetValue会返回Default(T)
  // FValue := Default(T);
end;
  1. 使用示例
var
  id : TNullable<integer>;
begin
  if Edit1.Text <> '' then
    id.Value := StrToInt(Edit1.Text)
  else
    id.Clear; // 主动置空
end;

方法2:新增静态Null属性(更直观)

如果想直接赋值为"空状态",可以给TNullable<T>添加静态属性:

  1. 修改接口部分
type
  TNullable<T> = record
  ...
  public
    ...
    class property Null: TNullable<T> read GetNull; // 新增静态属性
  end;
  1. 实现GetNull方法
class function TNullable<T>.GetNull: TNullable<T>;
begin
  // record默认初始化时FHasValue为nil,直接返回默认实例即可
  Result := Default(TNullable<T>);
end;
  1. 使用示例
var
  id : TNullable<integer>;
begin
  if Edit1.Text <> '' then
    id.Value := StrToInt(Edit1.Text)
  else
    id := TNullable<Integer>.Null; // 直接赋值为空状态
end;

原写法报错原因

  • id.Value := null:Value是Integer值类型,null是变体类型,无法直接转换,触发运行时错误。
  • id.Value := nil:nil是指针类型,与Integer类型不兼容,触发编译错误。

内容的提问来源于stack exchange,提问作者GuidoG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 12:55:56