Class/Static Constants in Delphi

前端 未结 9 740
粉色の甜心
粉色の甜心 2021-02-05 12:06

In Delphi, I want to be able to create an private object that\'s associated with a class, and access it from all instances of that class. In Java, I\'d use:

pub         


        
9条回答
  •  忘了有多久
    2021-02-05 12:45

    Here is how I'll do that using a class variable, a class procedure and an initialization block:

    unit MyObject;
    
    interface
    
    type
    
    TMyObject = class
       private
         class var FLogger : TLogLogger;
       public
         class procedure SetLogger(value:TLogLogger);
         class procedure FreeLogger;
       end;
    
    implementation
    
    class procedure TMyObject.SetLogger(value:TLogLogger);
    begin
      // sanity checks here
      FLogger := Value;
    end;
    
    class procedure TMyObject.FreeLogger;
    begin
      if assigned(FLogger) then 
        FLogger.Free;
    end;
    
    initialization
      TMyObject.SetLogger(TLogLogger.Create);
    finalization
      TMyObject.FreeLogger;
    end.
    

提交回复
热议问题