我是Java开发人员,我总是使用getter-setter方法。我怎样才能在Delphi中使用这个概念?
//1
//2
//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
。
(当我使用Eclipse在Java中开发时,我可以使用Source自动生成getter和setter方法 - >生成getter和setter ...)
答案 0 :(得分:13)
首先输入您想要的属性而不是内部变量。只需在类中创建以下类型即可
Property Colore : String Read GetColorText Write SetColorText;
然后按 Ctrl Shift C
然后,IDE将创建getter,setter和私有内部变量。请注意,Property Paster中的Property setter和getter是可选的。您可以轻松编写
Property Colore : String Read FColorText Write FColorText;
或只有一个二传手或吸气器
Property Colore : String Read FColorText Write SetColorText;
在这种情况下,IDE将生成私有FColorText
变量和setter方法SetColorText
答案 1 :(得分:2)
IDE中没有可以执行您想要的功能。
您可以使用 Ctrl + Shift + C 从property
声明生成getter和setter。但那些getter和setter是空的存根。
坦率地说,在我看来这是非常合理的行为。如何期望IDE知道您希望如何实现getter和setter。不能指望您打算使用哪个字段。您的代码很好地证明了为什么会如此。属性名称和字段名称之间没有明显的算法关系。
另一个要点是,如果您希望IDE自动生成问题中的getter和setter代码,为什么还要使用getter和setter?你写得很好:
property colore: string read ColorText write ColorText;
如果您希望能够使用您描述的功能,则需要找到实现该功能的Delphi扩展。显而易见的候选人是CnPack和GExperts。或者如果你找不到这样的扩展名,请自己写一个。
答案 2 :(得分:1)
您可以分三步完成此操作。
使用getter和变量定义属性以保存值:
property OnOff: Boolean Read GetOnOff Write fOnOff;
按Control + 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;
再次按Control + Shift + C以生成setter子组:
procedure TMyClass.SetOnOff(const Value: Boolean);
begin
fOnOff := Value;
end;
现在更改属性以使用getter和setter:
property OnOff: Boolean Read GetOnOff Write SetOnOff;
是的,这有点令人费解,但如果你有很多属性可以立即定义它可以帮助。