访问存储在另一个单元Delphi中的数据

时间:2010-04-13 15:01:46

标签: delphi class data-structures variables delphi-units

在我的程序的Unit2中,我有以下代码:

TValue = Record
  NewValue,
  OldValue,
  SavedValue : Double;
end; 

TData = Class(TObject)
Public
  EconomicGrowth : TValue;
  Inflation : TValue;
  Unemployment : TValue;
  CurrentAccountPosition : TValue;
  AggregateSupply : TValue;
  AggregateDemand : TValue;
  ADGovernmentSpending : TValue;
  ADConsumption : TValue;
  ADInvestment : TValue;
  ADNetExports : TValue;
  OverallTaxation : TValue;
  GovernmentSpending : TValue;
  InterestRates : TValue;
  IncomeTax : TValue;
  Benefits : TValue;
  TrainingEducationSpending : TValue;
End;

然后我在Var。中声明数据:TData。

当我尝试在Unit1中执行以下操作时:

  ShowMessage(FloatToStr(Unit2.Data.Inflation.SavedValue));

我收到了EAccessViolation消息。有没有办法从Unit1访问存储在'Data'中的数据而不会出错?

3 个答案:

答案 0 :(得分:6)

Data := TData.Create;添加到Unit2的initialization部分,或将TData更改为记录而不是对象。从Unit1访问Unit2的全局对象没有任何内在错误,只要它们被正确初始化。

答案 1 :(得分:1)

@ Hendriksen123,你在使用之前初始化变量Data吗? EAccessViolation是无效内存访问错误的异常类,通常在代码尝试访问尚未创建(已初始化)或已被销毁的对象时发生。

尝试使用Data := TData.Create;

然后您可以使用Data var。

答案 2 :(得分:0)

unit Unit2;

interface

type
  TValue = Record
    NewValue,
    OldValue,
    SavedValue : Double;
  end;

  TData = Class(TObject)
  Public
    EconomicGrowth : TValue;
    Inflation : TValue;
    Unemployment : TValue;
    CurrentAccountPosition : TValue;
    AggregateSupply : TValue;
    AggregateDemand : TValue;
    ADGovernmentSpending : TValue;
    ADConsumption : TValue;
    ADInvestment : TValue;
    ADNetExports : TValue;
    OverallTaxation : TValue;
    GovernmentSpending : TValue;
    InterestRates : TValue;
    IncomeTax : TValue;
    Benefits : TValue;
    TrainingEducationSpending : TValue;
  End;

procedure InitialiseData (var pData : TData);

implementation

procedure InitialiseData (var pData : TData);
begin
  pData := TData.Create;

  pData.EconomicGrowth.SavedValue := 1.00;

end;

end.

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Unit2,
  StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
var
  vData : TData;
begin
  Unit2.InitialiseData(vData);

  ShowMessage(FloatToStr(vData.EconomicGrowth.SavedValue));

end;

end.

有效