简体   繁体   English

为什么Delphi允许构造函数参数不正确?

[英]Why does Delphi allow constructor parameters to be incorrect?

This might seem like a really silly question, but I don't know why this is even allowed to compile: 这似乎是一个非常愚蠢的问题,但我不知道为什么甚至允许编译:

program ConstructorWithParam;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

type

  TThing = class(TObject)
  private
    FParent: TObject;
  public
    constructor Create(const AParent: TObject);
  end;

{ TThing }

constructor TThing.Create; // <- WTF? Why does the compiler not complain?
begin
  FParent := AParent;
end;

var
  Thing: TThing;
begin
  try
    Thing := TThing.Create(TObject.Create);
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

I'm using Delphi XE5 and have not tested on other versions. 我正在使用Delphi XE5并且没有在其他版本上测试过。 Thanks. 谢谢。

The first declaration in the form class is presumed to be the correct one. 表单类中的第一个声明被认为是正确的。 The implementation version does not need to identify the parameters required; 实现版本不需要识别所需的参数; they're assumed by the original declaration. 它们是由原始声明承担的。 This is a part of the language itself. 这是语言本身的一部分。

Here's a good example to illustrate the point: 这是一个很好的例子来说明这一点:

type
  TMyClass = class (Tobject)
    procedure DoSometimg(DoA, DoB: Boolean);
  end;

Implementation: 执行:

procedure TMyClass.DoSomething;   // Note both parameters missing
begin
  if DoA then    // Note not mentioned in implementation declaration
    DoOneThing;   // but still can be used here
  if DoB then
    DoAnotherThing;
end;

I personally prefer to make both the implementation and interface declarations match, because it makes it easier to identify the parameters without jumping around as much in the code editor. 我个人更喜欢使实现和接口声明匹配,因为它使得更容易识别参数而不会在代码编辑器中跳转。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM