Declare public global variable in Delphi

后端 未结 3 932
余生分开走
余生分开走 2021-01-01 21:47

Let\'s say I have two forms in a delphi project, I want to be able to access form1\'s variables from form2. Is there anyone to declare, say a \'public\' variable in form1 wh

3条回答
  •  走了就别回头了
    2021-01-01 22:09

    First, if you must use globals (it's probably better not to use globals, as Craig has wisely pointed out) then you should put the globals you want to share in SharedGlobals.pas:

    unit SharedGlobals;
    interface
    var
       {variables here}
       Something:Integer;
    implementation
        { nothing here?}
    

    Now use that unit, from the two units you want to share access to that variable in. Alternatively, have both reference another object, which is named something sensible, and have that object be designed, as the holder of state (variable values) that those two instances (forms or classes, or whatever) need to share.

    Second idea, since your two units that you have already have dependencies on each other, you could also get around your circular dependency by using the unit that would create a circular dependency, from the implementation section instead of the interface:

     unit Unit2;
     interface
       /// stuff
     implementation
        uses Unit1; 
    

    ...

     unit Unit1;
     interface
       /// stuff
     implementation
        uses Unit2; 
    

提交回复
热议问题