class function或class 類函數 類過程


 

class function或class

類函數\類過程.   它們是直接操作在類上面(沒有實例化的對象)   

下面是Delphi    Help    的描述   
    
   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 use Self 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.


類方法(Class methods)是一類特殊的方法,它們在聲明時要以 class 開頭:
    type
      TFigure = class
     public
     ...
   class procedure GetInfo(var Info: TFigureInfo); virtual;
       ...
     end;
  實現時也以 class 開頭:
 class procedure TFigure.GetInfo(var Info: TFigureInfo); 
 begin
  ...
  end;
  乍一看好象平時沒有遇到過這個東東,好象這個東東也沒有什么大作用,其實不然。比如我們有時為輸入密碼或其他常用數據專門做一個 Form,但由於其代碼都在 Form 定義的 unit 里面,所以在使用時僅僅需要幾行代碼,比如:
    with TfrmPassword.Create(nil) do
    try
  ShowModal;
 finally
 Free;
 end;
    雖然這樣的代碼已經很簡潔,但如果寫多了還是很討厭的。利用類方法可以使其更簡潔:
    TfrmPassword = class(TForm) 
    ...  
    public {Public declarations }  
    class function Execute: TModalResult;  
    end; 
    ...
 class function TfrmPassword.Execute: TModalResult; 
 begin
  with TfrmPassword.Create(nil) do 
     try
       Result :=ShowModal; 
     finally
      Release; //注意此處必須為release不能為free! 
     end; 
    end; 
 然后只用一行 TfrmPassword.Execute; 即可直接完成調用!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM