我有一個帶有多個變數的類,這些變數可以通過自己的屬性來訪問:
我有一個帶有多個變數的類,這些變數可以通過自己的屬性來訪問:
TGame = class(TObject)
strict private
FValue1 : 整數。
FValue2 : 整數。
private[/span
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,就像這樣:
propertyValue1 : Integer read GetValue write SetValue;
property Value2 : Integer read GetValue write SetValue;
uj5u.com熱心網友回復:
是的,這可以用索引指定器來實作:
索引指定器允許幾個屬性共享相同的訪問方法,同時代表不同的值。
例如,
span class="hljs-keyword">type
TTest = class
strict private
F值。array[0...1] of Integer;
function GetValue(Index: Integer): Integer;
procedure SetValue(Index: Integer; const Value: Integer);
public
property Value1: Integer index 0 read GetValuewrite SetValue;
property Value2: 整數 index 1 read GetValue write SetValue;
end;
{ TTest }
function TTest. GetValue(Index: Integer): Integer。
begin
結果 := FValues[Index] 。
end;
procedure TTest. SetValue(Index: Integer; const Value: Integer);
begin
FValues[Index] := Value;
end。
當然,這也適用于你原來的私有欄位:
type
TTest = class
strict private
FValue1:整數。
FValue2: 整數。
function GetValue(Index:Integer): Integer。
procedure SetValue(Index: Integer; const Value: Integer);
public
property Value1: Integer index 1 read GetValuewrite SetValue;
property Value2: 整數 index 2 read GetValue write SetValue;
end;
{ TTest }
function TTest. GetValue(Index: Integer): Integer。
begin
case Index of
1。
結果 := FValue1。
2:
結果 := FValue2。
else: 結果:=FValue2; else.
raise Exception.Create('Invalid index.' )。
end。
end;
procedure TTest. SetValue(Index: Integer; const Value: Integer);
begin
case Index of
1。
FValue1 :=價值。
2:
FValue2 := Value。
end;
end;
但是,幾乎看起來你更需要一個array屬性:
span class="hljs-keyword">type
TTest = class
strict private
F值。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
結果 := FValues[Index] 。
end;
procedure TTest. SetValue(Index: Integer; const Value: Integer);
begin
FValues[Index] := Value;
end。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/316510.html
標籤:
