如何自动生成getter和setter方法

pad*_*bro 5 delphi getter-setter

我是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.
Run Code Online (Sandbox Code Playgroud)

是否有自动创建getter和setter方法的功能?

我只想写colorText: string; //1和调用一个快捷方式,我希望IDE自动创建//2//3.

(当我使用Eclipse在Java中开发时,我可以使用Source - > Generate getter和setter自动生成getter和setter方法...)

And*_*y_D 13

首先输入您想要的属性而不是内部变量.只需在类中创建以下类型即可

Property Colore : String Read GetColorText Write SetColorText;

然后按 Ctrl Shift C

然后,IDE将创建getter,setter和private内部变量.

请注意,Property Paster中的Property setter和getter是可选的.你可以轻松写

Property Colore : String Read FColorText Write FColorText;

或只有一个二传手或吸气剂

Property Colore : String Read FColorText Write SetColorText;

在这种情况下,IDE将生成私有FColorText变量和setter方法SetColorText

  • @Teun,它不能.如果你有一个带有getter和setter的属性,那么你对后面的内容一无所知.如果你定义一个带有getter和setter字段的属性,例如`property ColorText:string read FColorText write SetColorText;`并按`CTRL + SHIFT + C`,那么生成的setter将包含该字段的简单赋值(至少在Delphi XE3中). (2认同)
  • @bradipo Getters和setter在Delphi中是可选的.您可以轻松地编写`Property Colore:String Read FColorText Write FColorText;`并且IDE将只生成私有变量.我会更新我的答案,指出这一点. (2认同)