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

24 Jun 2016

Share to:

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

เริ่มต้น DigitalOcean

มาทําความรู้จัก DigitalOcean กันก่อนDigitalOcean เป็น Simple Cloud Hosting คือผู้ให้บริการ Hosting ที่เราสามารถทําอะไรกับเครื่องได้ทุกอย่าง เหมือนกับว่าเรามีเครื่อง server มาใช้ทําอะไรก็ได้ตามที่เราต้องการ จุดเด่นของ DigitalOcean คือ ค่าบริการที่ถูกมาก เริ่มต้นเพียงเดือนละ $5 หรือ ประมาณ 180 บาท นอกจากค่าบริการที่ถูกแล้วยัง **ใช้งานง่าย **อีกด้วย หลังจากที่ผมได้ใช้งานมาสักพัก การ support ปัญหาต่างๆดีมาก

disable enable taskbar raspberry pi

วิธีเอา taskbar ของ raspberry pi ออก คือ ให้ย้ายไฟล์ "panel" ไปไว้ใน path อื่น โดยปกติไฟล์ "panel" จะอยู่ใน path "~/.config/lxpanel/LXDE/panels"

sql delete

sql delete เป็นคําสั่ง ที่ใช้ในการลบข้อมูลในตาราง โดยสามารถลบข้อมูลตามเงื่อนไข where ที่ผู้ใช้กําหนดDatabase supportMySQL, Microsoft Access, SQL Server, Oracleรูปแบบการใช้


Copyright © 2019 - 2024 thiti.dev |  v1.19.0 |  Privacy policy |  status | 

            วงแหวนเว็บ