This shows you the differences between two versions of the page.
| Both sides previous revision Previous revision | |||
|
tutorial:record [2019/01/28 10:13] admin |
tutorial:record [2019/01/28 10:14] (current) admin |
||
|---|---|---|---|
| Line 190: | Line 190: | ||
| ====Properties==== | ====Properties==== | ||
| - | คือ คุณสมบัติของ Object ประกอบไปด้วย Getter (คำสั่งหลัง read) และ Setter (คำสั่งหลัง write)\\ \\ | + | คือ คุณสมบัติของ Object โดยรายละเอียดจะขอกล่าวในหัวข้อ Class อีกที\\ \\ |
| - | เพื่อเป็นการอธิบายให้เห็นภาพ จะขอยกตัวอย่าง | + | |
| - | property ValueX:integer read GetValueX write SetValueX; | ||
| - | |||
| - | จากตัวอย่างดังกล่าว Getter คือ GetValueX ส่วน Setter คือ SetValueX \\ | ||
| - | Getter จะถูกเรียกใช้งาน เมื่อมีการเรียกใช้ค่าของ Property ดังเช่น | ||
| - | |||
| - | writeln(ValueX); | ||
| - | | ||
| - | Setter จะถูกเรียกใช้งาน เมื่อมีการใส่ค่าให้ Property เช่น | ||
| - | |||
| - | ValueX:=12; | ||
| - | | ||
| - | ทำไมต้องมี Getter Setter ให้ยุ่งยาก แทนที่จะใช้ var หรือ Field อย่างเดียว? ประโยชน์ของการใช้งาน Property มีดังนี้ครับ | ||
| - | *ใช้คัดกรองตัวแปร บางครั้งเรารับค่าเพื่อการคำนวณในช่วง 0-100 เท่านั้น หากผู้ใช้ใส่ค่าเกินกว่าค่าดังกล่าวมา จะสามารถคัดกรองให้เป็นค่าที่อยู่ในช่วง 0-100 แทนได้ | ||
| - | *เพื่อให้ค่าของ Property ได้มีการ update ตลอดเวลา โดยเฉพาะหาก property ของเรา ขึ้นอยู่กับค่าอื่น เมื่อใดที่มีการเปลี่ยนค่า ก็จะมีการ update ค่า property เราด้วยเสมอ | ||
| - | |||
| - | |||
| - | รูปแบบการเขียน Property มีหลักๆดังนี้ | ||
| - | *Property ที่มี Getter, Setter เป็น Field | ||
| - | |||
| - | property Value:integer read FValue write FValue; | ||
| - | |||
| - | *property ที่มี Getter, Setter เป็น Procedure/Function ซึ่งโดยปกติ Getter จะเป็น Function ส่วน Setter จะเป็น Procedure | ||
| - | |||
| - | property ValueX:integer read GetValueX write SetValueX; | ||
| - | function GetValueX:integer; | ||
| - | procedure SetValueX(Value:integer); | ||
| - | |||
| - | *Property ที่แสดงค่าได้อย่างเดียว (ReadOnly) | ||
| - | |||
| - | property IsOK:boolean read GetIsOK; | ||