如何在 Delphi 中自动生成getter和setter方法?

uurv41yg  于 2023-03-08  发布在  其他
关注(0)|答案(3)|浏览(220)

我是一个Java开发人员,我总是使用getter-setter方法。
如何在Delphi中使用这个概念?

  • 我定义了一个局部变量//1
  • 我创建了一个属性//2
  • 我按下CTRL + SHIFT + C,编辑器将创建getter和setter方法//3

对于这个例子:

unit Unit1;

type
  ClassePippo=class
  private
    colorText:string; //1
    function getColorText: String; //3
    procedure setColorText(const Value: String); //3
  public
    property colore: String read getColorText write setColorText;  //2
  end;

implementation

{ ClassePippo }

function ClassePippo.getColorText: String; //3
begin
  Result:=colorText;
end;

procedure ClassePippo.setColorText(const Value: String); //3
begin
  colorText:=Value;
end;

end.

是否有自动创建getter和setter方法的特性?
我只想编写colorText: string; //1并调用一个快捷方式,并且希望IDE自动创建//2//3
(When我使用Eclipse在Java中进行开发,我可以使用Source--〉Generate getter and setter ...自动生成getter和setter方法。)

qzwqbdag

qzwqbdag1#

首先输入你想要的属性而不是内部变量。在你的类中创建如下类型So
Property Colore : String Read GetColorText Write SetColorText;
然后按CtrlShift键C
IDE随后将创建getter、setter和私有内部变量。
注意属性setter和getter在Object Pascal中是可选的。
Property Colore : String Read FColorText Write FColorText;
或者只有一个setter或getter
Property Colore : String Read FColorText Write SetColorText;
在这种情况下,IDE将生成专用变量FColorText和setter方法SetColorText

jq6vz3qz

jq6vz3qz2#

IDE中没有可以满足您需要的功能。
可以使用Ctrl + Shift + C从property声明生成getter和setter,但这些getter和setter是空的存根。
坦率地说,在我看来,这是相当合理的行为。如何期望IDE知道您希望如何实现getter和setter?不能期望IDE知道您打算使用哪个字段。您的代码很好地演示了为什么会这样。属性名和字段名之间没有明显的算法关系。
要说明的另一点是,如果您希望IDE自动生成问题中getter和setter的代码,为什么还要为getter和setter费心呢?您完全可以这样编写:

property colore: string read ColorText write ColorText;

如果你希望能够使用你所描述的特性,你需要找到一个 Delphi 的扩展来实现这个特性。显而易见的候选者是CnPack和GEperts。或者如果你找不到这样的扩展,自己写一个。

ajsxfq5m

ajsxfq5m3#

您可以通过三个步骤完成此操作。
使用getter和保存值的变量定义属性:

property OnOff: Boolean Read GetOnOff Write fOnOff;

按Ctrl + Shift + C生成变量和getter sub:

private
fOnOff: Boolean;
function GetOnOff: Boolean;

...
还有

function TMyClass.GetOnOff: Boolean;
begin
  Result := fOnOff;
end;

现在更改属性以读取变量并使用setter进行写入:

property OnOff: Boolean Read fOnOff Write SetOnOff;

再次按Ctrl + Shift + C生成setter子对象:

procedure TMyClass.SetOnOff(const Value: Boolean);
begin
  fOnOff := Value;
end;

现在更改属性以使用getter和setter:

property OnOff: Boolean Read GetOnOff Write SetOnOff;

是的,这有点复杂,但是如果你有很多属性需要一次定义的话,这会很有帮助。

相关问题