User Tools

Site Tools


Sidebar


Introduction


Basic Tutorials


Advance Tutorials


Useful Techniques


Examples

  • Simple Pipe Weight Calculator
  • Unit Convertor

Sidebar

tutorial:genericandtemplate

This is an old revision of the document!


Generic And Template

Generic คืออะไร

คือการเขียนโปรแกรมให้สามารถใช้ได้กับหลากหลาย DataType โดยทั่วไปเรามักจะใช้ Generic กับการเขียนโปรแกรมดังนี้

  • Generic Procedure/Function
  • Generic Class

1. Generic Procedure/Function

คือการสร้าง Procedure/Function ที่รับค่า(หรือส่งค่า) Argument โดยไม่ได้ระบุ DataType เพื่อให้ Procedure/Function ดังกล่าว สามารถนำไปใช้ได้กับ DataType ที่หลากหลายนั่นเอง

รูปแบบการประกาศ สรุปได้ดังนี้

Topic Format
Generic Procedure
generic procedure ProcedureName<T>(Arg1:T);
begin
  {Do something}
end;
Generic Function
generic function FunctionName<T>(Arg1:T):T;
begin
  {Do something}
end;

การเรียกใช้ ทำได้ดังนี้

generalized 

Example-1: Generic Function สำหรับหาผลรวมของตัวแปร 2 ค่า

Example-1: Generic Function สำหรับหาผลรวมของตัวแปร 2 ค่า

generic function sum<T>(x,y:T):T;
begin
  result:=x+y;
end;


2. Generic Class

คือการสร้าง Class ที่ใช้กับ DataType ใดๆก็ได้ ไม่เฉพาะเจาะจง

tutorial/genericandtemplate.1545542501.txt.gz · Last modified: 2018/12/23 12:21 by admin