Delegate คืออะไร และใช้งานอย่างไร

24 Jun 2016,
Share: 

Delegate คืออะไร

Delegate จะเก็บตําแหน่ง Address ของ Method ที่ต้องการจะเรียกใช้ ทําให้เราสามารถเรียกใช้ Method ใดๆ ผ่าน Delegate ได้ คุณอาจจะสงสัยว่า ทําไมไม่เรียกใช้ Function ตรงๆไปเลย ข้อดีของการเรียกผ่าน Delegate คือสามารถเรียก Mathod ของ Class อื่นได้

Delegate ใช้งานอย่างไร

ตัวอย่างการใช้งาน ในบทความนี้ จะสร้างคลาส Class1 และคลาส Form1 โดยคลาส Class1 มี Delegate ชื่อว่า det สําหรับเรียกใช้ Method จากภายนอก ส่วนคลาส Form1 มี Method ชื่อ cal และ  Form_Load

Image

delegate class diagram การทํางานจะเริ่มจาก Form_Load โดยจะสร้าง Object ของคลาส Class1 หลังจากนั้นเรียก Method ชื่อ method1 โดยส่ง Adress ของ cal ไปให้กับ Delegate ในคลาส Class1 ทําให้คลาส Class1 สามารถเรียกใช้ Method cal จากคลาส Form_Load ได้ คลาส Class1

Public Class Class1

    Public Delegate Function det(ByVal x As Integer, ByVal y As Integer)

    Public Function method1(ByVal fnInput As det)

        MsgBox(fnInput(9, 1)) 'เรียก Method จากภายนอก

    End Function

End Class

คลาส Form1

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim obj As New Class1()
        obj.method1(AddressOf cal) 'เรียก Method ของคลาส Class1 โดยที่คลาส Class1 จะไปเรียก Method cal ของคลาส Form1

    End Sub

    Public Function cal(ByVal x As Integer, ByVal y As Integer) As Integer

        Return x + y

    End Function

End Class

Output:

Image

รูป Output   โหลด Project ตัวอย่าง>>> delegate example vs2008 ข้อมูลเพิ่มเติมที่>>>  artit-k.com/dev-callback-vb-net/

Suggestion blogs

Go EP.8 Go Channel Select Multiple Communication Operations

สวัสดีครับ ในบทความนี้ก็เป็น EP.8 แล้วนะครับ โดยเนื้อหาจะเป็นเรื่องเกี่ยวกับ Channel Select Multiple Communication Operationsสําหรับท่านใดที่ยังไม่ได้อ่าน EP.7 ท่านสามารถกลับไปอ่านก่อนได้นะครับที่นี่ Go EP.7 Go Unit Testingในบทความก่อนหน้านี้เราได้เรียนรู้เรื่องการใช้งาน Go Channel กันไปแล้ว จะเห็นว่าถ้าเราต้องการส่งข้อมูลมากกว่า 1 Channel อาจจะทําเกิด blocking การทำงาน เมื่อ Channel ใด Channel หนึ่งไม่มีการรับส่งข้อมูล หรือไม่สามารถส่งข้อมูลได้อีก สิ่งที่จะมาช่วยให้โปรแกรมของเราทํางานต่อไปได้ก็คือ Select statement เรามาดูวิธีการใช้งานตามหัวข้อด้านล่างเลยครับ

[ภาษาซี] การกําหนดค่าให้ตัวแปร

การกําหนดค่าให้กัยตัวแปรด้วยโอเปอเรเตอร์ ถือเป็นการดําเนินการอีกรูปแบบหนึ่ง สําหรับการกําหนดค่า (Assignment Operator) มีอยุ่หลายชนิดดังนี้

Arduino ตอน9 วิธีใช้ Analog output (PWM) ใน arduino

สวัสดีครับ วันนี้เราจะมาเรียนรู้การใช้งาน Analog output หรือ PWM ใน Arduino กันครับ โดยปกติแล้ว Arduino จะทํางานกับข้อมูลหรือ I/O ที่เป็นแบบ Digital HIGH/LOW (0V/5V) แต่ในบางกรณีเราอาจจําเป็นต้องใช้งาน I/O ที่เป็นแบบ Analog (0v, 1V, 2V...5V) เพื่อใช้ควบคุมอุปกรณ์ที่เป็นแบบ Analog เช่น ความสว่างของหลอดไฟ, ควบคุมความเร็วของ Motor ฯลฯ


Copyright © 2019 - 2025 thiti.dev |  v1.54.0 |  Privacy policy | 

Build with ❤️ and Astro.

Github profile   Linkedin profile   Instagram   X profile   Nostr   Youtube channel   Telegram   Email contact   วงแหวนเว็บ