You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Delphi类中不同属性能否共用同一个getter和setter访问器方法?

实现方案

完全可以实现,Delphi原生支持属性的index子句来满足这个需求,你可以给同类型的属性分配不同的索引标识,共用同一个Getter和Setter方法,通过索引区分要操作的成员变量。

改造后的代码示例

TGame = class(TObject)
   strict private
      FValue1 : Integer;
      FValue2 : Integer;
   private
      // 新增索引参数,用来区分当前操作的是哪个属性
      function GetValue(Index: Integer): Integer;
      procedure SetValue(Index: Integer; const Value: Integer);
   public
      // 每个属性指定唯一的index值,共用同一个读写方法
      property Value1 : Integer index 0 read GetValue write SetValue;
      property Value2 : Integer index 1 read GetValue write SetValue;
end;

// 实现共用的Getter
function TGame.GetValue(Index: Integer): Integer;
begin
  case Index of
    0: Result := FValue1;
    1: Result := FValue2;
  else
    Result := 0; // 可以根据需求加异常抛出或者默认处理
  end;
end;

// 实现共用的Setter
procedure TGame.SetValue(Index: Integer; const Value: Integer);
begin
  case Index of
    0: FValue1 := Value;
    1: FValue2 := Value;
  end;
end;

优化建议

如果你后续还会新增更多同类型的Integer属性,可以把成员变量直接改成数组存储,代码会更简洁,新增属性无需修改读写方法的逻辑:

TGame = class(TObject)
   strict private
      FValues: array[0..1] of Integer; // 索引0对应Value1,索引1对应Value2
   private
      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;
      // 新增Value3只需要加一行,修改数组长度即可
      // property Value3 : Integer index 2 read GetValue write SetValue;
end;

function TGame.GetValue(Index: Integer): Integer;
begin
  Result := FValues[Index];
end;

procedure TGame.SetValue(Index: Integer; const Value: Integer);
begin
  FValues[Index] := Value;
end;

注意事项

共用读写方法的属性必须是相同的数据类型,否则无法匹配方法的返回值和参数类型。

内容的提问来源于stack exchange,提问作者Maik Hasler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:48:01