Delphi的静态关键字是否在本机代码中有任何意义?

时间:2009-07-17 10:41:41

标签: delphi oop class

我的理解是引入了static关键字以与.NET兼容(以及strict

class TExample
  class procedure First;
  class procedure Second; static;

程序FirstSecond之间的差异是: -

  1. First可以在后代类中重写
  2. First传递一个引用TExample类的隐式self参数。
  3. 无法覆盖类过程Second并且不传递任何参数,因此与.NET兼容。因此,在原生代码中使用static关键字是否有任何意义,因为Delphi和amp;之间存在分歧。棱镜语法?

2 个答案:

答案 0 :(得分:21)

Static class methods have no hidden class reference argument。因此,它们与普通的旧函数指针兼容,因此可用于与Windows API和其他C API交互。例如:

type
  TForm = class
  private
    class function NonStaticWndProc (wnd: HWND; Message: Cardinal;
      wParam: WPARAM; lParam: LPARAM): LRESULT;
    class function StaticWndProc (wnd: HWND; Message: Cardinal;
      wParam: WPARAM; lParam: LPARAM): LRESULT; static;
    procedure RegisterClass;
  end;

procedure TForm.RegisterClass;
type
  TWndProc = function (wnd: HWND; Message: Cardinal;
    wParam: WPARAM; lParam: LPARAM): LRESULT;
var
  WP: TWndProc;
  WindowClass: WNDCLASS;
begin
  //WP := NonStaticWndProc; // doesn't work
  WP := StaticWndProc; // works
  // ...
  TWndProc (WindowClass.lpfnWndProc) := WP;
  Windows.RegisterClass (WindowClass);
end;

(当然,您可以使用全局函数,但除了全局函数之外,静态类函数与类有明确的关联。)

答案 1 :(得分:4)

静态,它快一点。方法First中有一个add esp, -8,而Second中没有。{/ p>

program staticTest;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  TExample=class
    class procedure First;
    class procedure Second; static;
  end;


{ TExample }

class procedure TExample.First;
var
  i : Integer;
begin
  i:=61374;
end;

class procedure TExample.Second;
var
  I : Integer;
begin
  i:=44510;
end;

begin
  { TODO -oUser -cConsole Main : Hier Code einfügen }
  TExample.First;
  TExample.Second;
end.

首先:

staticTest.dpr.20: begin
00408474 55               push ebp
00408475 8BEC             mov ebp,esp
00408477 83C4F8           add esp,-$08  ;This is the line I mentioned
0040847A 8945FC           mov [ebp-$04],eax
staticTest.dpr.21: i:=61374;
0040847D C745F8BEEF0000   mov [ebp-$08],$0000efbe
staticTest.dpr.22: end;
00408484 59               pop ecx
00408485 59               pop ecx
00408486 5D               pop ebp
00408487 C3               ret 

第二

staticTest.dpr.27: begin
00408488 55               push ebp
00408489 8BEC             mov ebp,esp
0040848B 51               push ecx
staticTest.dpr.28: i:=44510;
0040848C C745FCDEAD0000   mov [ebp-$04],$0000adde
staticTest.dpr.29: end;
00408493 59               pop ecx
00408494 5D               pop ebp
00408495 C3               ret 
00408496 8BC0             mov eax,eax

简而言之 - 我没有理由。