我有一个具有多个变量的类,这些变量可以通过它们自己的属性访问:
TGame = class(TObject)
strict private
FValue1 : Integer;
FValue2 : Integer;
private
procedure SetValue1(const Value : Integer);
procedure SetValue2(const Value : Integer);
function GetValue1() : Integer;
function GetValue2() : Integer;
public
property Value1 : Integer read GetValue1 write SetValue1;
property Value2 : Integer read GetValue2 write SetValue2;
我想知道,如果有一种方法可以使用相同的getter和setter不同的属性,像这样:
property Value1 : Integer read GetValue write SetValue;
property Value2 : Integer read GetValue write SetValue;
是的,这可以使用索引说明符来实现:
索引说明符允许多个属性在表示不同的值时共享相同的访问方法。
例如,
type
TTest = class
strict private
FValues: array[0..1] of Integer;
function GetValue(Index: Integer): Integer;
procedure SetValue(Index: Integer; const Value: Integer);
public
property Value1: Integer index 0 read GetValue write SetValue;
property Value2: Integer index 1 read GetValue write SetValue;
end;
{ TTest }
function TTest.GetValue(Index: Integer): Integer;
begin
Result := FValues[Index];
end;
procedure TTest.SetValue(Index: Integer; const Value: Integer);
begin
FValues[Index] := Value;
end;
当然,这也适用于你原来的私有字段:
type
TTest = class
strict private
FValue1: Integer;
FValue2: Integer;
function GetValue(Index: Integer): Integer;
procedure SetValue(Index: Integer; const Value: Integer);
public
property Value1: Integer index 1 read GetValue write SetValue;
property Value2: Integer index 2 read GetValue write SetValue;
end;
{ TTest }
function TTest.GetValue(Index: Integer): Integer;
begin
case Index of
1:
Result := FValue1;
2:
Result := FValue2;
else
raise Exception.Create('Invalid index.');
end;
end;
procedure TTest.SetValue(Index: Integer; const Value: Integer);
begin
case Index of
1:
FValue1 := Value;
2:
FValue2 := Value;
end;
end;
但是看起来你更需要一个数组属性:
type
TTest = class
strict private
FValues: array[0..1] of Integer;
function GetValue(Index: Integer): Integer;
procedure SetValue(Index: Integer; const Value: Integer);
public
property Values[Index: Integer]: Integer read GetValue write SetValue;
end;
{ TTest }
function TTest.GetValue(Index: Integer): Integer;
begin
Result := FValues[Index];
end;
procedure TTest.SetValue(Index: Integer; const Value: Integer);
begin
FValues[Index] := Value;
end;