gpt4 book ai didi

arrays - 在属性写入中引用一个公共(public) setter

转载 作者:行者123 更新时间:2023-12-03 18:09:15 30 4
gpt4 key购买 nike

我可以在属性的 write 访问器中引用一个通用的 setter _setTerm 而无需编写单独的 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

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;

您可能想检查 i 是否超出 _SetTerm 和 _GetTerm 的范围

关于arrays - 在属性写入中引用一个公共(public) setter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51927416/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com