4

彼のインスタンスと変数へのオフセットを使用して、クラスの厳密なプライベート クラス var値にアクセスする必要があります。

これまでにこれを試しました。このサンプルクラスを確認してください

type
  TFoo=class
   strict private class var Foo: Integer;
   public
   constructor Create;
  end;

constructor TFoo.Create;
begin
  inherited;
  Foo:=666;
end;

//this function works only if I declare the foo var as 
//strict private var Foo: Integer;
function GetFooValue(const AClass: TFoo): Integer;
begin
  Result := PInteger(PByte(AClass) + 4)^
end;

ご覧のとおり、関数 GetFooValue は、foo 変数がクラス var のように宣言されていない場合にのみ機能します。

問題は 、次のように宣言されているときGetFooValueの値を取得するために、どのように変更する必要があるかですFoostrict private class var Foo: Integer;

4

2 に答える 2

7

厳密なプライベート クラス var にアクセスするには、Class Helperレスキューします。

例 :

type
  TFoo = class
  strict private class var
    Foo : Integer;
  end;

  TFooHelper = class helper for TFoo
  private
    function GetFooValue : Integer;
  public
    property FooValue : Integer read GetFooValue;
  end;

function TFooHelper.GetFooValue : Integer;
begin
  Result:= Self.Foo;  // Access the org class with Self
end;

function GetFooValue( F : TFoo) : Integer;
begin
  Result:= F.GetFooValue;
end;

Var f : TFoo;//don't need to instantiate since we only access class methods

begin
  WriteLn(GetFooValue(f));
  ReadLn;
end.

質問に合うように例を更新しました。

于 2011-12-18T21:34:58.877 に答える
2

あなたは本当にそのようにすることはできません。クラス var はグローバル変数として実装され、そのメモリ位置は、プロセスのメモリの定数データ領域にあるクラス VMT の位置 (クラス参照が指すもの) と予測可能な関係を持ちません。

クラス外からこの変数にアクセスする必要がある場合はclass property、バッキング フィールドとして参照する を宣言します。

于 2011-12-18T21:35:24.103 に答える