我在此代码中通过引用传递值
Private Sub login()
Dim login As New login(lListClients, bConnected)
login.ShowDialog()
login.Dispose()
If (bConnected = True) Then
Console.WriteLine("Mokmeuh")
Button3.Visible = True
Button4.Visible = True
Button7.Visible = True
End If
End Sub
这是登录表单
Public Class login
Private lListClients As List(Of Client)
Private bConnected As Boolean
Sub New(ByRef lListClients As List(Of Client), ByRef bConnected As Boolean)
InitializeComponent()
Me.lListClients = lListClients
Me.bConnected = bConnected
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sID = TextBox1.Text, sPassword As String = TextBox2.Text
For Each cClient As Client In lListClients
If (Equals(cClient.getID, sID)) Then
If (Equals(cClient.getPassword, sPassword)) Then
bConnected = True
MessageBox.Show("Vous êtes connecté vous pouvez continuez")
Me.Close()
End If
Else
MessageBox.Show("Votre ID n'existe pas")
TextBox1.Clear()
TextBox2.Clear()
TextBox1.Focus()
End If
Next
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each m As Object In Me.Controls
If TypeOf m Is TextBox Then
CType(m, TextBox).Text = Nothing
End If
Next
Me.Close()
End Sub
Private Sub login_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Select()
End Sub
End Class
每当我启动它时,表单1中的bConnected值总是为false但是在登录表单中它在破坏时是真的所以我真的很困惑这里我已经通过引用传递了它应该的值,当在登录中设置为true时.vb,在form1.vb中也是如此,但条件If (bConnected = True)
永远不会成立。
所以我需要一些帮助,谢谢
顺便说一句:抱歉我的英文不好
答案 0 :(得分:1)
虽然您可以通过引用传递参数,但您无法存储这些引用。如果要更改参数的值,则必须在被调用的方法中执行此操作。否则,运行时无法确保变量仍然存活。
List(Of T)
已经是引用类型。因此,通过引用传递此参数通常是不合理的。变量lListClients
包含对实际列表对象的引用。按值传递变量时,会复制此引用并将其传递给方法,从而导致对同一对象的另一个引用。您希望通过引用传递此值的唯一原因是从被调用方法更改变量的值,即分配新列表。
您的问题的解决方案非常简单。创建一个公共属性:
Public Class login
Public Property Connected As Boolean
'...
Connected = True
'...
End Class
使用login
对象检查值:
If login.Connected Then
当然,在检查值之前,不应丢弃该对象。