是否可能存在两个名称相同的属性?

16

有没有可能有两个具有相同名称的属性?

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

好的,我尝试过了,编译器不允许我这样做,但也许有什么技巧可以解决?


"overload"也无济于事... - Gabriel
你可以在variantTField类型的参数中坚持一种方法,在方法本身中确定实际传递的类型。 - Lieven Keersmaekers
有点可能。请看我的回答... - HeartWare
3
我强烈建议您将已接受的答案更改为 @HeartWare 的答案。 - Jerry Dodge
1
你可以为Column定义一个记录(ColumnRec),并使用隐式类操作符来处理字符串和整数,以实现这一目的。property Cell[Column:ColumnRec; Row: Integer] - Sir Rufo
1个回答

31

不,但又可以说是:有点...

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;

关键是将属性命名相同,并使用“default”子句标记两个属性。然后,您可以使用各种参数访问相同的属性名称:

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

编译没问题。不知道它是否得到了官方支持或是否存在其他问题,但是它可以编译并调用正确的getter/setter(在Delphi 2010中测试过)。

当然,这仅适用于您的类尚未使用默认属性的情况,因为我唯一能够使其起作用的方法是通过default子句。


1
是的,这是官方支持的。默认属性允许您将类作为数组访问。重载允许您以不同的方式访问“数组”。由于参数类型不同,编译器能够消除正确的重载歧义。......当然,为什么对于非默认数组属性不允许却是个谜。 - Johan
谢谢您的观察。阅读您的答案真的很有趣。您认为,可以使用泛型来实现这个目的吗?我目前正在考虑使用TDictionary<T> - asd-tm
4
我学到了新知识,已点赞!http://docwiki.embarcadero.com/RADStudio/Seattle/en/Properties#Array_Properties一个类只能有一个特定签名(数组参数列表)的默认属性,但可以对默认属性进行重载。在派生类中更改或隐藏默认属性可能会导致意外行为,因为编译器总是静态地绑定到属性。 - fantaghirocco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接