Thema: Delphi Maßeinheiten als Typen

Einzelnen Beitrag anzeigen

Benutzerbild von Uwe Raabe
Uwe Raabe

Registriert seit: 20. Jan 2006
Ort: Lübbecke
11.007 Beiträge
 
Delphi 12 Athens
 
#14

AW: Maßeinheiten als Typen

  Alt 11. Okt 2018, 10:18
Unter Verwendung der Units System.ConvUtils und System.StdConvs kann man da recht einfach was zaubern:
Delphi-Quellcode:
type
  TGramm = type Double;
  TKilogramm = type Double;

  TWeight = record
  private
    FConv: TConvType;
    FValue: Double;
  public
    constructor Create(AValue: Double; AConv: TConvType);
    class operator Implicit(A: TWeight): TGramm; overload;
    class operator Implicit(A: TGramm): TWeight; overload;
    class operator Implicit(A: TWeight): TKilogramm; overload;
    class operator Implicit(A: TKiloGramm): TWeight; overload;
    property Conv: TConvType read FConv write FConv;
    property Value: Double read FValue write FValue;
  end;

constructor TWeight.Create(AValue: Double; AConv: TConvType);
begin
  FValue := AValue;
  FConv := AConv;
end;

class operator TWeight.Implicit(A: TWeight): TGramm;
begin
  Result := Convert(A.Value, A.Conv, muGrams);
end;

class operator TWeight.Implicit(A: TGramm): TWeight;
begin
  Result := TWeight.Create(A, muGrams);
end;

class operator TWeight.Implicit(A: TWeight): TKilogramm;
begin
  Result := Convert(A.Value, A.Conv, muKilograms);
end;

class operator TWeight.Implicit(A: TKiloGramm): TWeight;
begin
  Result := TWeight.Create(A, muKilograms);
end;
Natürlich kannst du dir auch selbst deine Einheiten und Konvertierungen erstellen, aber es gibt halt mit den oben genannten Units schon einen vorgefertigten Mechanismus dafür.

Das Konvertieren geht dann über ein Cast auf TWeight:
Delphi-Quellcode:
procedure TuWas(const Value: TGramm); overload;
var
  K: TKiloGramm;
begin
  K := TWeight(Value);
  Writeln(Format('%1.3f g = %1.3f Kg', [Value, K]));
end;

procedure TuWas(const Value: TKiloGramm); overload;
var
  K: TGramm;
begin
  K := TWeight(Value);
  Writeln(Format('%1.3f Kg = %1.3f g', [Value, K]));
end;
Delphi-Quellcode:
var
  A: TKiloGramm;
  B: TGramm;
  C: TTonnen;
begin
  A := 50;
  B := 1500;
  TuWas(A);
  TuWas(B);
  TuWas(C); // Fehlermeldung: Doppeldeutiger überladener Aufruf von 'TuWas'
end;
Uwe Raabe
Certified Delphi Master Developer
Embarcadero MVP
Blog: The Art of Delphi Programming
  Mit Zitat antworten Zitat