[기타] [vb.net] 델리 게이트(Delegate) 선언 방법과 간단한 예제

회원사진
하나를하더라도최선을
2022-11-30 15:40 2,653 0

본문



*델리 게이트(Delegate)

- 대리자 로써 C 언어나 C++ 언어를 공부한 사람이라면 쉽게 접할 수 있는 함수 포인터와 비슷한 기능을 합니다. 또한 콜백 함수 기능 역할도 수행

*델리 게이트 선언 방법과 간단한 예제
 

Public Class Form1
 
    Delegate Function DelegateFunctionA(ByVal a As Integer, ByVal b As Integer) As Integer
    Delegate Function DelegateFunctionB(ByVal a As Integer) As String
    Delegate Sub DelegateSubA(ByVal a As Integer, ByVal b As Integer)
 
    Private Sub Button1_Click(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles Button1.Click
        Dim dfa As DelegateFunctionA = New DelegateFunctionA(AddressOf FunctionA)
        MsgBox(dfa(56).ToString() + " , Delegate 함수 사용")
    End Sub
 
    Private Sub Button2_Click(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles Button2.Click
        Dim dfa As DelegateSubA = New DelegateSubA(AddressOf SubA)
        dfa(56)
    End Sub
 
    Private Sub Button3_Click(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles Button3.Click
        Dim dfa As DelegateFunctionB = New DelegateFunctionB(AddressOf FunctionB)
        MsgBox(dfa(5))
    End Sub
 
    Private Function FunctionA(ByVal a As Integer, ByVal b As Integer) As Integer
        Return a + b
    End Function
 
    Private Sub SubA(ByVal a As Integer, ByVal b As Integer)
        MsgBox((a + b).ToString())
    End Sub
 
    Private Function FunctionB(ByVal a As Integer) As String
        Return a.ToString()
    End Function
 
End Class


위 코드와 같이 델리 게이트 선언 형식과 함수 형식이 같으며

만약 리턴 형식 및 전달 인자 형식이 틀리게 되면 오류가 발생하게 됩니다.

간략히 델리 게이트가 무엇이며, 간단한 예제를 만들어 봤습니다. 

댓글목록0

등록된 댓글이 없습니다.