這僅僅是一個具體案件的一個非常簡單的例子,但是,它仍然是一個很常見的情況。
如果您有一個可視化控件,當您更改變量/屬性時,可能需要重新繪製控件。例如,假設您的控件具有BackgroundColor
變量/屬性。
加入這樣一個變量/屬性的最簡單方法是讓它成爲一個公共變量:
TMyControl = class(TCustomControl)
public
BackgroundColor: TColor;
...
end;
而在TMyControl.Paint
過程中,你畫使用BackgroundColor
值的背景。但是這並不是。因爲如果更改控件實例的BackgroundColor
變量,控件不會重新繪製自身。相反,新的背景顏色將不會被使用,直到下次由於某種其他原因控件重新繪製時爲止。
所以,你必須做這樣的:
TMyControl = class(TCustomControl)
private
FBackgroundColor: TColor;
public
function GetBackgroundColor: TColor;
procedure SetBackgroundColor(NewColor: TColor);
...
end;
其中
function TMyControl.GetBackgroundColor: TColor;
begin
result := FBackgroundColor;
end;
procedure TMyControl.SetBackgroundColor(NewColor: TColor);
begin
if FBackgroundColor <> NewColor then
begin
FBackgroundColor := NewColor;
Invalidate;
end;
end;
,然後使用該控件的程序員使用MyControl1.GetBackgroundColor
獲取的顏色,並使用MyControl1.SetBackgroundColor
設置它。尷尬了。
使用屬性,你可以擁有兩全其美。事實上,如果你從視程序員的角度做
TMyControl = class(TCustomControl)
private
FBackgroundColor: TColor;
procedure SetBackgroundColor(NewColor: TColor);
published
property BackgroundColor: TColor read FBackgroundColor write SetBackgroundColor;
end;
...
procedure TMyControl.SetBackgroundColor(NewColor: TColor);
begin
if FBackgroundColor <> NewColor then
begin
FBackgroundColor := NewColor;
Invalidate;
end;
end;
然後
- ,他可以讀取和使用單一標識,
MyControl1.BackgroundColor
屬性設置背景顏色,以及
- 控制當他設置時重新塗漆!
Magicmaster - 我必須在這裏失去一些東西;你能解釋一下如何爲你的示例TSampleClass.SomeInfo定義一個getter和setter,並且當你爲SomeInfo變量賦值或者讀取值時,實際上會調用這些方法嗎? – Stuart
看到這個問題:http://stackoverflow.com/q/3963874/267938 –