机房收费系统 之 委托登录

        忘记了具体的时间,具体的地点应该是在511。老师提了这么一句“以后你们的代码里面都不能有调用,全部都有委托”。如果我没有记错的话,好像是这么说的......如果我记错了的话,也有可能是我听错了哈......

        最近开始机房收费系统合作版,然后就想着能不能把委托这个东西加到咱们的机房中来,然后就在那里查资料啊,查资料!反正查了一天多......最后,功夫不负有心人,终于搞定了!

        虽然是实现了功能,但是真的不确定自己这样做到底是正确的还是错误的!这个还有待老师和师哥师姐们给出宝贵的意见!

        委托是什么我就不说的了,不懂的可以看看C# 之 委托,虽然写的不是特别的详细,但是看了也能了解个大概。现在就让我们来看看具体的代码实现:

我们熟悉的D层代码:

Imports System.Data.SqlClient
Public Class DAL

    Public Function Login(ByVal strUserID As String, ByVal strPassword As String) As Boolean
        '创建一个SqlConnection
        Dim conn As New SqlConnection("server=.;database=ChargeSystem;uid=sa;pwd=123456")

        '创建一个SqlCommand从数据库中查询该用户名和密码是否存在
        Dim cmd As New SqlCommand("select count(*) from T_User where userID='" & strUserID & "' and password='" & strPassword & "'", conn)
        conn.Open()
        Dim count As Integer = cmd.ExecuteScalar()
        conn.Close()

        If count > 0 Then
            Return True '用户名和密码正确
        Else
            Return False
        End If
    End Function
End Class

再看看新的B层:

Public Class BLL
    '声明委托LoginEventHandler,此时委托所代表的方法有两个参数,返回值为布尔值
    Public Delegate Function LoginEventHandler(ByVal strUserID As String, ByVal strPassword As String) As Boolean

    Public Function Login(ByVal strUserID As String, ByVal strPassword As String) As Boolean
        Dim dal As New DAL
        '将DAL类中的Login方法添加到委托loginEventHandler
        Dim loginEventHandler As LoginEventHandler = AddressOf dal.Login
        Dim flag As Boolean

        flag = loginEventHandler(strUserID, strPassword)
        Return flag

    End Function
End Class

最后看看新的U层:

Public Class Form1
    '声明委托LoginEventHandler,此时委托所代表的方法有两个参数,返回值为布尔值
    Public Delegate Function LoginEventHandler(ByVal strUserID As String, ByVal strPassword As String) As Boolean
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
        Dim bll As New BLL
        Dim loginEventHandler As LoginEventHandler
        Dim strUserID As String = txtUserID.Text.Trim()
        Dim strPassword As String = txtPassword.Text.Trim()
        Dim flag As Boolean

        '将DAL类中的Login方法添加到委托loginEventHandler
        loginEventHandler = AddressOf bll.Login

        flag = loginEventHandler(strUserID, strPassword)

        If flag = True Then
            MsgBox("终于登陆成功!")
        Else
            MsgBox("用户名或密码输入错误!")
            txtPassword.Text = ""
            txtUserID.Focus()
            txtUserID.SelectAll()

        End If

    End Sub

    Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
        Me.Close()

    End Sub
End Class

最后看看我们的结果:

机房收费系统 之 委托登录_第1张图片


    在VB.NET中事件不能用具有返回类型的委托类型来声明,这点和C#不一样!然后就是这一点点的区别就花费了我好多的精力!不过最后还是做出来了,真的非常的高兴!嘿嘿......







你可能感兴趣的:(delegate,VB.NET)