Einzelnen Beitrag anzeigen

Benutzerbild von Sir Rufo
Sir Rufo

Registriert seit: 5. Jan 2005
Ort: Stadthagen
9.454 Beiträge
 
Delphi 10 Seattle Enterprise
 
#6

AW: Mehrdimensionale Variable variabler Dimension

  Alt 11. Okt 2014, 14:50
Warum nicht so?
Delphi-Quellcode:
unit DimValue;

interface

uses
  System.Generics.Collections;

type
  IVariable<T> = interface
    function GetValue: T;
    procedure SetValue( const Value: T );
    property Value: T read GetValue write SetValue;
    function GetV( index: Integer ): IVariable<T>;
    procedure SetV( index: Integer; Value: IVariable<T> );
    property V[index: Integer]: IVariable<T> read GetV write SetV; default;
  end;

  TVariable<T> = class( TInterfacedObject, IVariable<T> )
  private
    FValue: T;
    FVarDict: TDictionary<Integer, IVariable<T>>;
  private
    function GetValue: T;
    procedure SetValue( const Value: T );
    function GetV( index: Integer ): IVariable<T>;
    procedure SetV( index: Integer; Value: IVariable<T> );
  private
    constructor Create;
    destructor Destroy; override;
  public
    class function Construct: IVariable<T>;
  end;

implementation

{ TVariable<T> }

class function TVariable<T>.Construct: IVariable<T>;
begin
  Result := TVariable<T>.Create;
end;

constructor TVariable<T>.Create;
begin
  inherited;
  FVarDict := TDictionary < Integer, IVariable < T >>.Create;
end;

destructor TVariable<T>.Destroy;
begin
  FVarDict.Free;
  inherited;
end;

function TVariable<T>.GetV( index: Integer ): IVariable<T>;
begin
  if not FVarDict.TryGetValue( index, Result )
  then
    begin
      Result := TVariable<T>.Construct;
      FVarDict.Add( index, Result );
    end;
end;

function TVariable<T>.GetValue: T;
begin
  Result := FValue;
end;

procedure TVariable<T>.SetV( index: Integer; Value: IVariable<T> );
begin
  FVarDict.AddOrSetValue( index, Value );
end;

procedure TVariable<T>.SetValue( const Value: T );
begin
  FValue := Value;
end;

end.
Jetzt hast du eine beliebige Dimensoinstiefe.
Delphi-Quellcode:
procedure foo;
var
  LVar : IVariable<string>;
begin
  LVar := TVariable<string>.Construct;
  LVar[0].Value := 'foo';
  LVar[0][0].Value := 'bar';
  LVar[0][0][0].Value := 'foobar';

  WriteLn( LVar[0].Value, ',', LVar[0][0].Value, ',', LVar[0][0][0].Value ); // => foo,bar,foobar
end;
Kaum macht man's richtig - schon funktioniert's
Zertifikat: Sir Rufo (Fingerprint: ‎ea 0a 4c 14 0d b6 3a a4 c1 c5 b9 dc 90 9d f0 e9 de 13 da 60)
  Mit Zitat antworten Zitat