如何在vb.net中创建一个干净和简短的代码

时间:2016-04-06 08:59:06

标签: vb.net

我在Stack Overflow上很新,这是我第一次提出问题所以如果你发现这个问题很愚蠢或任何事情,请对我好心。

有谁知道如何缩短这些代码,我的意思是我想将所有这些代码放在一行..请参阅下面的代码。

Private Sub PB_SearchP_MouseHover(sender As Object, e As EventArgs) Handles PB_SearchP.MouseHover
    PB_SearchP.Image = My.Resources.search1
End Sub

Private Sub PB_SearchP_MouseLeave(sender As Object, e As EventArgs) Handles PB_SearchP.MouseLeave
    PB_SearchP.Image = My.Resources.search
End Sub

Private Sub PB_AddP_MouseHover(sender As Object, e As EventArgs) Handles PB_AddP.MouseHover
    PB_AddP.Image = My.Resources.add_1_iconhover
End Sub

Private Sub PB_AddP_MouseLeave(sender As Object, e As EventArgs) Handles PB_AddP.MouseLeave
    PB_AddP.Image = My.Resources.add_1_icon
End Sub

Private Sub PB_New_MouseHover(sender As Object, e As EventArgs) Handles PB_New.MouseHover
    PB_New.Image = My.Resources.newhover
End Sub

Private Sub PB_New_MouseLeave(sender As Object, e As EventArgs) Handles PB_New.MouseLeave
    PB_New.Image = My.Resources.neww
End Sub

Private Sub PB_Save_MouseHover(sender As Object, e As EventArgs) Handles Btn_Save.MouseHover
    Btn_Save.Image = My.Resources.savehover
End Sub

Private Sub PB_Save_MouseLeave(sender As Object, e As EventArgs) Handles Btn_Save.MouseLeave
    Btn_Save.Image = My.Resources.save
End Sub

Private Sub PB_Update_MouseHover(sender As Object, e As EventArgs) Handles BTN_QUpdate.MouseHover
    BTN_QUpdate.Image = My.Resources.edithover
End Sub

Private Sub PB_Update_MouseLeave(sender As Object, e As EventArgs) Handles BTN_QUpdate.MouseLeave
    BTN_QUpdate.Image = My.Resources.edit
End Sub

1 个答案:

答案 0 :(得分:1)

更简单的解决方案是使用将lamba函数设置为事件处理程序的函数:

Public Shared Sub SetUpButton(btn As Button, normalImage As Image, hoverImage as Image)

    AddHandler btn.MouseLeave, Sub(o, e) btn.Image = normalImage
    AddHandler btn.MouseHover, Sub(o, e) btn.Image = hoverImage

End Sub

这样称呼:

SetUpButton( Btn_Save, My.Resources.save, My.Resources.savehover )
SetUpButton( Btn_Update, My.Resources.update, My.Resources.updatehover )
SetUpButton( Btn_New, My.Resources.new, My.Resources.newhover )

依旧......

在C#中,进行语法比较:

public static void SetUpButton(Button btn, Image normalImage, Image hoverImage) {
    btn.MouseLeave += (o,e) => btn.Image = normalImage;
    btn.MouseHover += (o,e) => btn.Image = hoverImage;
}