delphi中的单位是否与其他语言中的类相同?

die*_*lar 1 delphi class delphi-units

我需要编写一些Delphi代码,但我之前没有使用Delphi的经验.我见过人们编写一些代码,称为unit1unit2使用其中的代码导入它.那么,我可以将该单元视为Java或C#中的类吗?

Mas*_*ler 6

不是.单位是Delphi中的源代码文件.您基本上可以将其视为命名空间,其范围与当前文件完全相同.

在单元内,您可以使用类型定义语法定义类.它看起来像这样:

type
  TMyClass = class(TParentClass)
  private
    //private members go here
  protected
    //protected members go here
  public
    //public members go here
  end;
Run Code Online (Sandbox Code Playgroud)

任何方法都声明在类型声明下面,而不是内联,这使代码更容易阅读,因为您可以一目了然地看到类的组成,而不必通过它的实现.

此外,每个单元有两个主要部分,称为接口实现.类型声明可以放在任一部分中,但实现代码在接口中无效.这允许类似于Java或C#的公共和私有类的语言概念:在接口中声明的任何类型对于使用该单元的其他单元("public")是可见的,而在实现中声明的任何类型仅在同一单元内可见.


J..*_*... 6

添加到梅森的答案 - 一般的单位结构看起来像这样:

Unit UnitName;    
  interface
    //forward declaration of classes, methods, and variables)
    uses 
      //list of imported dependencies needed to satisfy interface declarations
      Windows, Messages, Classes;
    const 
      // global constants
      THE_NUMBER_THREE = 3;
    type // declaration and definition of classes, type aliases, etc 
      IDoSomething = Interface(IInterface)
        function GetIsFoo : Boolean;
        property isFoo : Boolean read GetIsFoo;
      end;
      TMyArray = Array [1..5] of double;
      TMyClass = Class(TObject)
        //class definition
        procedure DoThis(args : someType);
      end;
      TAnotherClass = Class(TSomethingElse)
        //class definition
      end;        
    //(global methods)
    function DoSomething(arg : Type) : returnType;        
    var  //global variables
      someGlobal : boolean;      
  implementation
    uses
      //list of imported dependencies needed to satisfy implementation
    const
      //global constants with unit scope (visible to units importing this one)
    type
      //same as above, only visible within this or importing units
    var
      //global variables with unit scope (visible to units importing this one) 
    procedure UnitProc(args:someType)
    begin
      //global method with unit scope, visible within this or importing units
      //note no forward declaration!
    end;       
    procedure TMyClass.DoThis(args : someType)
    begin
      //implement interface declarations
    end;
    function DoSomething(arg : Type) : returnType;    
    begin
      // do something
    end;
  initialization
    //global code - runs at application start 
  finalization
    //global code - runs at application end
end. // end of unit
Run Code Online (Sandbox Code Playgroud)

显然,每个单元都不需要所有这些部分,但我认为这些都是可以包含的所有部分.当我第一次进入Delphi时我花了一段时间来计算所有这些,我可能会对这样的地图做得很好所以我提供它以防它有用.