我有一个派生自Form的类,它有用户名和密码的文本框和一个OK按钮。我希望它的行为类似于InputBox,所以我可以像这样使用它:
Dim Username As String = ""
Dim Password As String = ""
Dim authorization As New Authorization(Username, Password)
authorization.ShowDialog()
'The user will click OK and I will expect the Username and Password to change based on the user input
MsgBox(Username & " " & Password)
授权类:
Public Class Authorization
Dim RefUsername As String
Dim RefPassword As String
Public Sub New(ByRef Username As String, ByRef Password As String)
InitializeComponent()
RefUsername = Username 'I'm trying to pass reference instead of value
RefPassword = Password 'I'm trying to pass reference instead of value
End Sub
Private Sub OKButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AuthorizeButton.Click
RefUsername = Username.Text 'I'm trying to change value of variable outside the class
RefPassword = Password.Text 'I'm trying to change value of variable outside the class
Me.Close()
End Sub
End Class
简而言之,我想在用户单击OK时更改类外变量的值,我将如何实现?
答案 0 :(得分:1)
Public Class Authorization
Dim RefUsername As String
Dim RefPassword As String
Public Sub New(ByRef Username As String, ByRef Password As String)
InitializeComponent()
RefUsername = Username 'I'm trying to pass reference instead of value
RefPassword = Password 'I'm trying to pass reference instead of value
End Sub
Private Shared Function PromptUser() As ReturnClass
Dim currentReturnClass as ReturnClass
// Dialog Goes Here
currentReturnClass.UserName = Username.Text
currentReturnClass.Password = Password.Text
Me.Close()
End Sub
End Class
private class ReturnClass
Dim userName as String
Dim password as String
Dim userAcceptedDialog as Boolean
' Setters and Getters
End Class
您的主叫代码:
Dim Username As String = "Default User"
Dim Password As String = "Default Password"
Dim authorization As New Authorization(Username, Password)
Dim myReturnClass as ReturnClass
myReturnClass = authorization.PromptUser()
MsgBox(myReturnClass.Username & " " & myReturnClass.Password)
答案 1 :(得分:1)
您可以向类中添加属性,以便像在任何其他类一样从外部修改它:
Public Class Authorization
Friend Property RefUsername As String
Friend Property RefPassword As String
'this constructor isn't really necessary with this new approach,
'but I'll leave it as-is.
Public Sub New(ByRef Username As String, ByRef Password As String)
InitializeComponent()
RefUsername = Username '
RefPassword = Password
End Sub
Private Sub OKButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles AuthorizeButton.Click
Me.DialogResult = DialogResult.OK
End Sub
End Class
然后从外面获取用户名和密码:
Dim Username As String = ""
Dim Password As String = ""
Dim authorization As New Authorization(Username, Password)
'this constructor isn't really necessary with this new approach,
'but I'll leave it as-is.
If authorization.ShowDialog() = DialogResult.OK Then
MsgBox(authorization.RefUsername & " " & authorization.RefPassword)
End If