vb.net 如何从另一种形式调用公共函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28930320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call a public function from another form
提问by Caesium95
Frm1contains the code for validation of textbox:
Frm1包含用于验证的代码textbox:
Public Function AlphabeticalOnly(ByVal Str As String) As Boolean
Dim pattern As String = "^[a-zA-Z\s]+$"
Dim reg As New Regex(pattern)
If reg.IsMatch(Str) = False Then
MsgBox(Str & " is invalid! Please enter alphabetical characters only!", MsgBoxStyle.Critical, "Error")
End If
Return reg.IsMatch(Str)
End Function
Because there're quite an amount of validations, I don't want to repeat all the code again in the other forms.
因为有相当多的验证,我不想在其他表单中再次重复所有代码。
Private Sub btnDone_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDone.Click
If AlphabeticalOnly(txtName.Text) = False Then
Exit Sub
End If
...
End Sub
I tried the code above in another form, but the error list shows that AlphabeticalOnlyis not declared.
我以另一种形式尝试了上面的代码,但错误列表显示AlphabeticalOnly未声明。
Is there anything that I need to add to my code?
有什么我需要添加到我的代码中的吗?
回答by David
First of all, don't put the function on a form. If it's common code shared by all forms, put it in its own class file.
首先,不要把函数放在一个表单上。如果它是所有表单共享的公共代码,请将其放在自己的类文件中。
Second, this common code shouldn't be prompting the user with a message box. This function shouldjust perform the logic and nothing more. (This also makes the function easier to unit test.) Then allow the consuming code (in this case a form) to interact with the user. (Especially since the current implementation checks the match twice, which isn't necessary.)
其次,这个通用代码不应该用消息框提示用户。这个函数应该只执行逻辑,仅此而已。(这也使函数更易于单元测试。)然后允许使用代码(在本例中为表单)与用户交互。(特别是因为当前的实现检查匹配两次,这是没有必要的。)
Since this function doesn't rely on object state, you can make it Shared. Something like this:
由于此函数不依赖于对象状态,因此您可以将其设为Shared. 像这样的东西:
Public Class CommonFunctions
Public Shared Function IsAlphabeticalOnly(ByVal Str As String) As Boolean
Dim pattern As String = "^[a-zA-Z\s]+$"
Dim reg As New Regex(pattern)
Return reg.IsMatch(Str)
End Function
End Class
Then on your forms you can invoke that function:
然后在您的表单上,您可以调用该函数:
If CommonFunctions.IsAlphabeticalOnly(txtName.Text) = False Then
MsgBox(Str & " is invalid! Please enter alphabetical characters only!", MsgBoxStyle.Critical, "Error")
End If

