Class/Static Constants in Delphi

前端 未结 9 732
粉色の甜心
粉色の甜心 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:54

    For what I want to do (a private class constant), the neatest solution that I can come up with (based on responses so far) is:

    unit MyObject;
    
    interface
    
    type
    
    TMyObject = class
    private
      class var FLogger: TLogLogger;
    end;
    
    implementation
    
    initialization
      TMyObject.FLogger:= TLogLogger.GetLogger(TMyObject);
    finalization
      // You'd typically want to free the class objects in the finalization block, but
      // TLogLoggers are actually managed by Log4D.
    
    end.
    

    Perhaps a little more object oriented would be something like:

    unit MyObject;
    
    interface
    
    type
    
    TMyObject = class
    strict private
      class var FLogger: TLogLogger;
    private
      class procedure InitClass;
      class procedure FreeClass;
    end;
    
    implementation
    
    class procedure TMyObject.InitClass;
    begin
      FLogger:= TLogLogger.GetLogger(TMyObject);
    end;
    
    class procedure TMyObject.FreeClass;
    begin
      // Nothing to do here for a TLogLogger - it's freed by Log4D.
    end;
    
    initialization
      TMyObject.InitClass;
    finalization
      TMyObject.FreeClass;
    
    end.
    

    That might make more sense if there were multiple such class constants.

提交回复
热议问题