動態指定事件之重要觀念

有關Delphi 的語法, 程式, 等
回覆文章
頭像
tim
文章: 1380
註冊時間: 2008年 11月 26日, 00:49

動態指定事件之重要觀念

文章 tim »

動態指定 event 要注意的小地方, 傳入的不是 procedure 而是 procedure of object. 克服這個問題, 可以利用一個虛擬的 class 如下例如示, 該 class 中僅設定 class function, 用來設定使用!!
記得宣告時要加上 class 保留字. 附上的說明是 delphi 5 的 on-line help 內容!

語法:

代碼: 選擇全部

     
    unit Unit1; 
     
    interface 
     
    uses 
      Windows, Messages, SysUtils, Classes, Graphics, Controls, forms, Dialogs, 
      StdCtrls; 
     
    type 
      TmyMsg = class 
        class procedure my(Sender: TObject); 
      end; 
      Tform1 = class(Tform) 
        Button1: TButton; 
        Button2: TButton; 
        procedure Button1Click(Sender: TObject); 
      private 
        { Private declarations } 
      public 
        { Public declarations } 
      end; 
     
    var 
      form1: Tform1; 
     
     
    implementation 
     
    {$R *.DFM} 
     
    procedure Tform1.Button1Click(Sender: TObject); 
    begin 
      Button2.onClick := TmyMsg.my; 
    end; 
     
    class procedure TmyMsg.my(Sender: TObject); 
    begin 
      showmessage('my'); 
    end; 
     
    end. 
     
     
     
     
    A class method is a method (other than a constructor) that operates on classes instead of objects. The definition of a class method must begin with the reserved word class. For example, 
     
    type 
     
      TFigure = class 
      public 
        class function Supports(Operation: string): Boolean; virtual; 
        class procedure GetInfo(var Info: TFigureInfo); virtual; 
        ... 
      end; 
     
    The defining declaration of a class method must also begin with class. For example, 
     
    class procedure TFigure.GetInfo(var Info: TFigureInfo); 
     
    begin 
      ... 
    end; 
     
    In the defining declaration of a class method, the identifier Self represents the class where the method is called (which could be a descendant of the class in which it is defined). If the method is called in the class C, then Self is of the type class of C. Thus you cannot useSelf to access fields, properties, and normal (object) methods, but you can use it to call constructors and other class methods. 
    A class method can be called through a class reference or an object reference. When it is called through an object reference, the class of the object becomes the value of Self. 
多多留言, 整理文章, 把經驗累積下來.....
回覆文章