在属性写入中引用一个常见的setter

时间:2018-08-20 09:06:31

标签: arrays delphi setter

我可以在属性的_setTerm访问器中引用一个公共的setter write,而无需编写单独的setter方法_setTerm1_setTerm2_setTerm3吗?

TAdder = class(TCalculatorComponent)
private
  _terms: array[1..10] of OleVariant;
  procedure _setTerm(const i: Integer; const Value: OleVariant);
  procedure _setTerm1(const Value: OleVariant);
  procedure _setTerm2(const Value: OleVariant);
  procedure _setTerm3(const Value: OleVariant);
  .......
public
  constructor Create(AOwner: TComponent); override;
  property Term1: OleVariant read _terms[1] write _setTerm1;
  property Term2: OleVariant read _terms[2] write _setTerm2;
  property Term3: OleVariant read _terms[3] write _setTerm3;
  .......
end;

implementation

procedure TAdder._setTerm(const i: Integer; const Value: OleVariant);
begin
  _terms[i] := TVarConv.NullableFloat(Value);
  _calculate();
end;

procedure TAdder._setTerm1(const Value: OleVariant);
begin
  _setTerm(1, Value);
end;

procedure TAdder._setTerm2(const Value: OleVariant);
begin
  _setTerm(2, Value);
end;

procedure TAdder._setTerm3(const Value: OleVariant);
begin
  _setTerm(3, Value);
end;

1 个答案:

答案 0 :(得分:9)

解决方案#1

type
  TAdder = class
  private
    _terms: array[1..10] of OleVariant;
    procedure _setTerm(const i: Integer; const Value: OleVariant);
    function _getTerm(const Index: Integer): OleVariant;
public
  property Term1: OleVariant index 1 read _getTerm write _SetTerm;
  property Term2: OleVariant index 2 read _getTerm write _SetTerm;
  property Term3: OleVariant index 3 read _getTerm write _SetTerm;
end;

function TAdder._getTerm(const Index: Integer): OleVariant;
begin
  Result := _terms[i];
end;

procedure TAdder._setTerm(const i: Integer; const Value: OleVariant);
begin
  _terms[i] := TVarConv.NullableFloat(Value);
  _calculate();
end;

解决方案2

type
  TAdder = class
  private
  _terms: array[1..10] of OleVariant;
    procedure _setTerm(i: Integer; const Value: OleVariant);
    function _getTerm(Index: Integer): OleVariant;

public
  property Terms[aIndex: Integer]: OleVariant read _getTerm write _SetTerm;
end;


function TAdder._getTerm(Index: Integer): OleVariant;
begin
  Result := _terms[Index];
end;

procedure TAdder._setTerm(i: Integer; const Value: OleVariant);
begin
  _terms[i] := TVarConv.NullableFloat(Value);
  _calculate();
end;

您可能要检查我是否不在_SetTerm和_GetTerm范围内