【问题标题】:Is it possible to have two properties with the same name?是否可以有两个同名的属性?
【发布时间】:2015-12-11 14:11:39
【问题描述】:

是否可以有两个同名的属性?

property  Cell [Cl, Rw: Integer]: string   read getCell  write setCell;
property  Cell [ColName: string; Rw: Integer]: string read getCellByCol write setCellByCol;

好吧,我试过了,编译器不让我这样做,但也许有一个技巧......?

【问题讨论】:

  • 'overload' 也无济于事......
  • 您可以坚持使用带有variantTField 之类的参数的方法,您可以在其中确定方法本身中实际传递的类型。
  • 可能的 - 有点。看我的回答...
  • 我强烈建议您将接受的答案更改为@HeartWare 的答案
  • 您可以为 Column 定义一条记录,其中包含字符串和整数的隐式类运算符来实现此目的。 property Cell[Column:ColumnRec; Row: Integer]

标签: delphi delphi-xe7


【解决方案1】:

不-但又一次:是的...有点...

function    getP1(Cl,Rw : integer) : string;
procedure   setP1(C1,Rw : integer ; const s : string);
function    getP2(const Cl : string ; Rw : integer) : string;
procedure   setP2(const C1 : string ; Rw : integer ; const s : string);
property    P1[Cl,Rw : integer] : string read getP1 write setP1; default;
property    P1[const Cl : string ; Rw : integer] : string read getP2 write setP2; default;

诀窍是将属性命名为相同,并用“默认”子句标记两者。然后您可以使用各种参数访问相同的属性名称:

P1['k',1]:=P1[2,1];
P1[2,1]:=P1['k',1];

编译良好。不知道这是否受到官方支持或是否存在其他问题,但它编译良好并调用正确的 getter/setter(在 Delphi 2010 中测试)。

这当然只有在你还没有为你的类使用默认属性的情况下才有效,因为我能够使它工作的唯一方法是通过默认子句。

【讨论】:

  • 是的,这是官方支持的。默认属性允许您以数组的形式访问该类。重载允许您以不同的方式访问“数组”。因为参数类型不同,编译器能够消除正确的重载。 .....当然,为什么不允许非默认数组属性对我来说是个谜。
  • 感谢您的观察。阅读您的答案真的很有趣。您如何看待,那么是否可以为此目的使用泛型?我目前正在考虑TDictionary<T>
  • 赞成,我学到了新东西! docwiki.embarcadero.com/RADStudio/Seattle/en/… 一个类只能有一个具有给定签名(数组参数列表)的默认属性,但可以重载默认属性。更改或隐藏后代类中的默认属性可能会导致意外行为,因为编译器总是静态绑定到属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
  • 2011-10-09
  • 2011-01-01
相关资源
最近更新 更多