Delphi中重复的setter逻辑

Tih*_*uan 9 delphi pascal delphi-2006

对于类的每个setter,我必须实现一些事件逻辑(OnChanging,OnChanged):

procedure TBlock.SetWeightIn(const Value: Double);
var OldValue: Double;
begin
  OldValue := FWeightIn;
  DoOnChanging(OldValue, Value);
  FWeightIn := Value;
  DoOnChanged(OldValue, Value);
end;

procedure TBlock.SetWeightOut(const Value: Double);
var OldValue: Double;
begin
  OldValue := FWeightOut;
  DoOnChanging(OldValue, Value);
  FWeightOut := Value;
  DoOnChanged(OldValue, Value);
end;
Run Code Online (Sandbox Code Playgroud)

你能否建议一种方法来实现这一点,而不必为每个setter重复所有这些行?

Cob*_*ger 13

试试这个:

procedure TBlock.SetField(var Field: Double; const Value: Double);
var
    OldValue: Double;
begin
    OldValue := Field;
    DoOnChanging(OldValue, Value);
    Field := Value;
    DoOnChanged(OldValue, Value);
end;

procedure TBlock.SetWeightIn(const Value: Double);
begin
    SetField(FWeightIn, Value);
end;

procedure TBlock.SetWeightOut(const Value: Double);
begin
    SetField(FWeightOut, Value);
end;
Run Code Online (Sandbox Code Playgroud)


Rob*_*edy 7

Delphi支持索引属性.多个属性可以共享一个getter或setter,由序数索引区分:

type
  TWeightType = (wtIn, wtOut);
  TBlock = class
  private
    procedure SetWeight(Index: TWeightType; const Value: Double);
    function GetWeight(Index: TWeightType): Double;
  public
    property InWeight: Double index wtIn read GetWeight write SetWeight;
    property OutWeight: Double index wtOut read GetWeight write SetWeight;
  end;
Run Code Online (Sandbox Code Playgroud)

您可以将此与Cobus的答案结合起来得到:

procedure TBlock.SetWeight(Index: TWeightType; const Value: Double);
begin
  case Index of
    wtIn: SetField(FWeightIn, Value);
    wtOut: SetField(FWeightOut, Value);
  end;
end;
Run Code Online (Sandbox Code Playgroud)

这可能会为您提供有关通过索引引用字段的其他方法的建议,而不是为这些相关值提供两个完全独立的字段.