如何从类中的属性中获取值

时间:2014-02-05 03:08:23

标签: vb.net class properties get

我在Form1中有以下代码,其中我将Value设置为属性:

Dim login As New logInSession
Dim k As String
login.saveLogInfo = unameTB.Text

这是我的logInSession类中的代码,我将存储值:

Private logInfo As String

Public Property saveLogInfo() As String
    Get
        Return logInfo
    End Get
    Set(ByVal value As String)
        logInfo = value
    End Set
End Property

现在,我希望将值恢复到我的Form2。问题是它没有返回任何值。以下是我的代码:

Dim login As New logInSession
Dim k As String
k = login.saveLogInfo
MsgBox(k)

你能告诉我我的代码有什么问题吗?

2 个答案:

答案 0 :(得分:1)

Dim login As New logInSession // HERE
Dim k As String
k = login.saveLogInfo
MsgBox(k)

此代码会创建logInSession类的 new 实例。因此,每次尝试访问login.saveLogInfo属性时,它都是默认值(空字符串)。您需要使用您在此处创建的原始对象:

Dim login As New logInSession
Dim k As String
login.saveLogInfo = unameTB.Text

答案 1 :(得分:1)

那是因为你有两个不同的logInSession类实例。一个位于Form1,另一个位于Form2。这是一个例子:

Dim login As New logInSession
'you have 1 logInSession instance here, and set it's property
login.saveLogInfo = "Some Text"

Dim anotherLogin As New logInSession
'but later you check property of another instance of logInSession
Dim k = anotherLogin.saveLogInfo
'here you get empty string
Console.WriteLine(k)

'you need to, in some way, pass the first instance instead of creating new instance
Dim referenceToFirstInstance As logInSession = login
k = anotherLogin.saveLogInfo
'here you get "Some Text"
Console.WriteLine(k)

how to pass data between forms

上查看此参考