delphi - 为什么缺少可选参数会导致 "Incompatible types"错误

标签 delphi generics optional-parameters type-constraints

有人可以解释一下为什么当我省略构造函数的可选参数时,在以下程序中出现“不兼容类型”错误(Delphi XE3)(有关详细信息,请参阅代码底部的注释)?

program Test;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  System.Classes;

type
  BaseClass = class(TObject);

  ChildClass = class(BaseClass);

  GenericBaseClass<T> = class
  public
    constructor Create(Fixed: Integer);
  end;

  GenericClass<T: BaseClass> = class(GenericBaseClass<T>)
  public
    type
      TMyProc = procedure (DataObject: T) of object;
  public
    constructor Create(Fixed: String; Optional: TMyProc = nil);
  end;

constructor GenericClass<T>.Create(Fixed: String; Optional: TMyProc);
begin
  inherited Create(12);
end;

constructor GenericBaseClass<T>.Create(Fixed: Integer);
begin
  inherited Create();
end;

var
  Gc: GenericClass<ChildClass>;

begin
  // this call is okay
  Gc := GenericClass<ChildClass>.Create('', nil);
  // this call fails: E2010 Incompatible types: 'ChildClass' and 'T'
  Gc := GenericClass<ChildClass>.Create('');
end.

最佳答案

reintroduceoverload 添加到 GenericClass 构造函数,因为您有多个具有相同名称但参数不同的构造函数。

关于delphi - 为什么缺少可选参数会导致 "Incompatible types"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16794525/

相关文章:

c# - 为什么在 C# 中使用泛型约束

c# - 重写继承方法时避免显式类型转换

javascript - 有没有办法在 JavaScript 的函数调用中提供命名参数?

virustotal api 的 Json 解析结果

ssh - 系统命令执行但立即后台

windows - 移动无边框样式的表单

c# - 自定义 icomparer 错误 - 无法从用法中推断出类型参数

c# - C# 4.0 以及可选参数和重载的组合是否会向您发出有关歧义的警告?

不传递可选参数的 C# 存储过程

Delphi GUI 测试和模态表单