我正在浏览一些旧的VB代码,我遇到了像这样的函数定义 -
Private Function ExistingCustomer(Index As Integer, Customer As String) As Integer
Private Sub cmdCustomerList_Click()
Run Code Online (Sandbox Code Playgroud)
有什么不同?
Lel*_*mbo 110
函数返回值,Sub没有.就这么简单.
D. *_*ott 18
函数也可以用在表达式中.子程序不能.函数可以比子例程更好地提供代码的可读性.
以下是函数如何提高可读性的示例:
If AccountIsLocked("JJones") then Msgbox("This account is locked")
Run Code Online (Sandbox Code Playgroud)
这个函数将在某处定义
public function AccountIsLocked(UserId as string) as boolean
dim usr = uow.AccountRepository.UserInfo(UserId)
return usr.locked
end function
Run Code Online (Sandbox Code Playgroud)
这是相同的例子,但用子程序编码:
CheckIfAccountLocked("JJones")
Run Code Online (Sandbox Code Playgroud)
和其他地方这个子定义:
public sub CheckIfAccountLocked(UserId)
if uow.AccountRepository.UserInfo(UserId).locked then
msgbox("Account is locked")
end if
end sub
Run Code Online (Sandbox Code Playgroud)
另请注意,检查值与操作是分开的 - 这有助于职责分离.该功能将提供可重用性.
使用VB6,有一些奇怪的规则来控制括号.如果sub没有参数,则不需要括号(我认为Visual Studio可能会删除括号).解决此问题的一种方法是在sub之前添加关键字"Call".
Call CheckIfAccountLocked()
Run Code Online (Sandbox Code Playgroud)
VS
CheckIfAccountLocked
Run Code Online (Sandbox Code Playgroud)