AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79552245
Accepted
GuidoG
GuidoG
Asked: 2025-04-03 15:17:07 +0800 CST2025-04-03 15:17:07 +0800 CST 2025-04-03 15:17:07 +0800 CST

如何将可空整数设置为空?

  • 772

我已经创建了一个像这样的可空类型,这是我在 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 ,该怎么办?怎么做?

delphi
  • 2 2 个回答
  • 120 Views

2 个回答

  • Voted
  1. Remy Lebeau
    2025-04-04T01:05:44+08:002025-04-04T01:05:44+08:00

    nullVariant是类型的const VT_NULL,这就是为什么您会收到与转换相关的运行时错误Variant。您想要的nil是。

    但是,当 a 不是指针类型时,您不能将 a 赋值nil给 a 。因此,要执行所需的操作,您需要更新以接受指针作为输入。TTNullable<T>T^

    从 Delphi 2006 开始,record可以重载运算符,因此您无需通过Value属性接受赋值。您可以重载转换运算符,以便将T值和T^指针转换为Nullable<T>(并转换Nullable<T>为T值),然后您就可以将nil指针分配给Nullable变量,例如:

    unit NullableType;
    
    interface
    
    type
      TNullable<T> = record
      public
        type PointerOfT = ^T; // <-- add this
      private
        FValue: T;
        FHasValue: IInterface;
    
        function GetHasValue: Boolean;
    
        procedure SetValue(const AValue: T);
        procedure SetValueByPointer(const AValue: PointerOfT);
        procedure SetToNil;
      public
        constructor Create(const AValue: T); overload;
        constructor Create(const AValue: PointerOfT); overload; // <-- add this
    
        // add these...
        class operator Implicit(const Src: TNullable<T>): T;
        class operator Implicit(const Src: T): TNullable<T>;
        class operator Implicit(const Src: PointerOfT): TNullable<T>;
    
        class operator Explicit(const Src: TNullable<T>): T;
        class operator Explicit(const Src: T): TNullable<T>;
        class operator Explicit(const Src: PointerOfT): TNullable<T>;
        //
    
        property HasValue: Boolean read GetHasValue;
        property Value: T read FValue write SetValue; // <-- optional now!
    
        function ToString: string;
      end;
    
    implementation
    
    uses
      System.SysUtils, System.Rtti;
    
    constructor TNullable<T>.Create(const AValue: T);
    begin
      SetValue(AValue);
    end;
    
    constructor TNullable<T>.Create(const AValue: PointerOfT);
    begin
      SetValueByPointer(AValue);
    end;
    
    class operator TNullable<T>.Implicit(const Src: TNullable<T>): T;
    begin
      Result := Src.FValue;
    end;
    
    class operator TNullable<T>.Implicit(const Src: T): TNullable<T>;
    begin
      Result.SetValue(Src);
    end;
    
    class operator TNullable<T>.Implicit(const Src: PointerOfT): TNullable<T>;
    begin
      Result.SetValueByPointer(Src);
    end;
    
    class operator TNullable<T>.Explicit(const Src: TNullable<T>): T;
    begin
      Result := Src.FValue;
    end;
    
    class operator TNullable<T>.Explicit(const Src: T): TNullable<T>;
    begin
      Result.SetValue(Src);
    end;
    
    class operator TNullable<T>.Explicit(const Src: PointerOfT): TNullable<T>;
    begin
      Result.SetValueByPointer(Src);
    end;
    
    procedure TNullable<T>.SetValue(const AValue: T);
    begin
      FValue := AValue;
      FHasValue := TInterfacedObject.Create;
    end;
    
    procedure TNullable<T>.SetValueByPointer(const AValue: PointerOfT);
    begin
      if AValue <> nil then
        SetValue(AValue^)
      else
        SetToNil;
    end;
    
    procedure TNullable<T>.SetToNil;
    begin
      FValue := Default(T);
      FHasValue := nil;
    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 := StrToInt(Edit1.Text)
      else
        id := nil;
    

    此外,从 Delphi 10.4 开始,您可以使用自定义管理记录来替换IInterface简单的Boolean,例如:

    • 的使用IInterface基于 Allen Bauer 撰写的一篇旧博客文章IInterface,该文章早于 CMR 的推出。他甚至在文章中指出,CMR 可以解决他用作解决方法的问题!
    unit NullableType;
    
    interface
    
    type
      TNullable<T> = record
      public
        type PointerOfT = ^T;
      private
        FValue: T;
        FHasValue: Boolean; // <-- change this
    
        procedure SetValue(const AValue: T);
        procedure SetValueByPointer(const AValue: PointerOfT);
        procedure SetToNil;
      public
        constructor Create(const AValue: T); overload;
        constructor Create(const AValue: PointerOfT); overload;
    
        class operator Initialize(out Dest: TNullable<T>); // <-- add this
    
        class operator Implicit(const Src: TNullable<T>): T;
        class operator Implicit(const Src: T): TNullable<T>;
        class operator Implicit(const Src: PointerOfT): TNullable<T>;
        class operator Explicit(const Src: TNullable<T>): T;
        class operator Explicit(const Src: T): TNullable<T>;
        class operator Explicit(const Src: PointerOfT): TNullable<T>;
    
        property HasValue: Boolean read FHasValue;
        property Value: T read FValue write SetValue;
    
        function ToString: string;
      end;
    
    implementation
    
    uses
      System.SysUtils, System.Rtti;
    
    constructor TNullable<T>.Create(const AValue: T);
    begin
      SetValue(AValue);
    end;
    
    constructor TNullable<T>.Create(const AValue: PointerOfT);
    begin
      SetValueByPointer(AValue);
    end;
    
    class operator TNullable<T>.Initialize(out Dest: TNullable<T>);
    begin
      Dest.SetToNil;
    end;
    
    class operator TNullable<T>.Implicit(const Src: TNullable<T>): T;
    begin
      Result := Src.FValue;
    end;
    
    class operator TNullable<T>.Implicit(const Src: T): TNullable<T>;
    begin
      Result.SetValue(Src);
    end;
    
    class operator TNullable<T>.Implicit(const Src: PointerOfT): TNullable<T>;
    begin
      Result.SetValueByPointer(Src);
    end;
    
    class operator TNullable<T>.Explicit(const Src: TNullable<T>): T;
    begin
      Result := Src.FValue;
    end;
    
    class operator TNullable<T>.Explicit(const Src: T): TNullable<T>;
    begin
      Result.SetValue(Src);
    end;
    
    class operator TNullable<T>.Explicit(const Src: PointerOfT): TNullable<T>;
    begin
      Result.SetValueByPointer(Src);
    end;
    
    procedure TNullable<T>.SetValue(const AValue: T);
    begin
      FValue := AValue;
      FHasValue := True;
    end;
    
    procedure TNullable<T>.SetValueByPointer(const AValue: PointerOfT);
    begin
      if AValue <> nil then
        SetValue(AValue^)
      else
        SetToNil;
    end;
    
    procedure TNullable<T>.SetToNil;
    begin
      FValue := Default(T);
      FHasValue := False;
    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.
    

    如果您需要支持旧版本的 Delphi,那么只需IFDEF相应地编写代码即可。

    • 3
  2. Best Answer
    HeartWare
    2025-04-03T15:37:54+08:002025-04-03T15:37:54+08:00

    由于您使用接口来检测它是否具有值,因此我会这样做:

    PROCEDURE TNullable<T>.SetNull;
      BEGIN
        FHasValue:=NIL
      END;
    
    FUNCTION TNullable<T>.IsNull : BOOLEAN;
      BEGIN
        Result:=NOT Assigned(FHasValue)
      END;
    

    您不能通过赋值来完成此操作(或者您可以 - 声明一个接受指针值但只允许NIL作为值的赋值运算符,然后调用SetNull。如果您尝试分配非NIL指针,则会引发异常)。

    • 1

相关问题

  • 如何删除 TMS Web Core 项目上的“未经许可的试用版”消息?[关闭]

  • 为什么 TIdHTTP.Head() 生成“HTTP/1.1 406 不可接受”异常?

  • TTreeView:如何仅选中/取消选中 TTreeNode 中的子级?

  • 如何从当前光标所在位置开始查找?

  • 在 delphi/RAD studio/C++ builder 中使用 Rust 语言?[关闭]

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve