User Tools

Site Tools


tutorial:genericandtemplate

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
Last revision Both sides next revision
tutorial:genericandtemplate [2018/12/23 10:54]
admin [Generic คืออะไร]
tutorial:genericandtemplate [2018/12/23 23:15]
admin
Line 5: Line 5:
   * Generic Procedure/​Function ​   * Generic Procedure/​Function ​
   * Generic Class   * Generic Class
-  
  
-\\ +=====1. Generic Procedure/​Function===== 
 +คือการสร้าง Procedure/​Function ที่รับค่า(หรือส่งค่า) Argument โดยไม่ได้ระบุ DataType เพื่อให้ Procedure/​Function ดังกล่าว สามารถนำไปใช้ได้กับ DataType ที่หลากหลายนั่นเอง ​\\ 
 + 
 +รูปแบบการประกาศ สรุปได้ดังนี้ 
 + 
 +^  Topic  ^  Format ​ ^  
 +|Generic Procedure|<​sxh delphi;>​ 
 +generic procedure ProcedureName<​T>​(Arg1:​T);​ 
 +begin 
 +  {Do something} 
 +end; 
 +</​sxh>​ | 
 +|Generic Function|<​sxh delphi;>​ 
 +generic function FunctionName<​T>​(Arg1:​T):​T;​ 
 +begin 
 +  {Do something} 
 +end; 
 +</​sxh>​ | 
 + 
 +การเรียกใช้ สมตติว่าเราจะนำมาใช้กับ integer จะเรียกใช้ได้ดังนี้ 
 + 
 +  specialize FunctionName<​integer>​(x):​  
 + 
 + 
 +<hidden Example-1: Generic Function สำหรับหาผลรวมของตัวแปร 2 ค่า>​ 
 +<sxh delphi;>​ 
 +generic function sum<​T>​(x,​y:​T):​T;​ 
 +begin 
 +  result:​=x+y;​ 
 +end; 
 + 
 +var x,​y:​double;​ 
 + 
 +Begin 
 + ​x:​=12.78;​ 
 + ​y:​=9.86;​ 
 + ​writeln('​sum(x,​y) = ',​specialize sum<​double>​(x,​y));​ 
 + 
 +End. 
 +</​sxh> ​     
 +</​hidden>​  
 + 
 +\\ 
 + 
 +**__หมายเหตุ__** - Generic Function ปัจจุบันสามารถใช้ได้เฉพาะ Lazarus เวอร์ชั่น Trunk (สำหรับ Developer) เท่านั้น ยังไม่สามารถใช้ได้กับเวอร์ชั่นทั่วไป 
 + 
 +=====2. Generic Class===== 
 +คือการสร้าง Class ที่ใช้กับ DataType ใดๆก็ได้ ไม่เฉพาะเจาะจง คล้ายกับ Generic Procedure/​Function แต่เปลี่ยนเป็น Class เท่านั้น แต่สำหรับ Generic Class นั้น ก่อนการนำไปใช้ จะต้องมีการสร้าง Class เป้าหมาย ขึ้นมาก่อนเสมอ รูปแบบของการประกาศและการสร้าง Class สรุปได้ดังนี้ 
 + 
 +^  Topic  ^  Format ​ ^  
 +|การประกาศ Generic Class|<​sxh delphi;>​ 
 +type 
 +  generic TList<​T>​ = class 
 +    Items: array of T; 
 +    procedure Add(Value: T); 
 +  end; 
 +</​sxh>​ | 
 +|การสร้าง Class จาก Generic Class|<​sxh delphi;>​ 
 +Type   
 +  TIntegerList = specialize TList<​Integer>;​ 
 +  TPointerList = specialize TList<​Pointer>;​ 
 +  TStringList = specialize TList<​string>;​ 
 +</​sxh>​ |
tutorial/genericandtemplate.txt · Last modified: 2018/12/23 23:16 by admin