如何在将类转换为类型vb.net时创建类的新实例

时间:2015-01-08 18:20:10

标签: wpf vb.net serialization

我有一个名为SettingsForProgram的Serializable类,这个类包含一个名为ServerList的字符串列表 我正在使用这个类保存myprogram(用户名,密码,颜色等)的设置但是当我尝试以相同的方式保存列表然后从中添加-or get-项目时,我得到的对象引用未设置为实例对象所以如何在转换它时创建类的新实例

要理解我的意思,这里有一些代码:

班级:

<Serializable()>
Public Class SettingsForProgram
Private Namev As String = ""
Private pwv As String = ""
Public LocationsList As New List(Of String)
Private Savev As New Boolean()
Public Property LoginName As String
    Get
        Return Namev
    End Get
    Set(value As String)
        Namev = value
    End Set
End Property
Public Property LoginPassword As String
    Get
        Return pwv
    End Get
    Set(value As String)
        pwv = value
    End Set
End Property
Public Property SaveLogin As Boolean
    Get
        Return Savev
    End Get
    Set(value As Boolean)
        Savev = value
    End Set
End Property
Public Sub New()
    LocationsList = New List(Of String)
End Sub
End Class

加载设置:(我想初始化类的新实例)

public MySettings as new SettingsForProgram
Public Sub LoadSettings()
    Dim formatter As New BinaryFormatter()
    Dim data As Byte() = File.ReadAllBytes(savepath)
    Dim ms As New MemoryStream(data)
    MySettings = CType(formatter.Deserialize(ms), SettingsForProgram)
End Sub

保存设置:

Public Sub SaveSettings()
    Dim bf As New BinaryFormatter()
    Dim ms As New MemoryStream()
    If MySettings.LoginName = Nothing Then
        MySettings.LoginName = "name"
    ElseIf MySettings.LoginPassword = Nothing Then
        MySettings.LoginPassword = "password"
    End If
    bf.Serialize(ms, MySettings)
    Dim mySaveState As Byte() = ms.ToArray()
    File.WriteAllBytes(savepath, mySaveState)
End Sub

我做了一个像这样的快速测试

按钮1:保存

MySettings.LocationsList.AddRange({"test1", "test2", "test3"}) <<<< where i get the error
 SaveSettings()

按钮2:加载

 LoadSettings()
  MsgBox(MySettings.LocationsList(1))

1 个答案:

答案 0 :(得分:0)

感谢#Steve,我现在知道了这个问题 ,解决方案是像我一样保存名称和密码, 刚刚将其添加到保存设置

If MySettings.LocationsList Is Nothing Then
        MySettings.LocationsList = New List(Of String)
        MySettings.LocationsList.Add("Location 1")
End If

并且每件事都有效

最终代码

Public Sub SaveSettings()
    Dim bf As New BinaryFormatter()
    Dim ms As New MemoryStream()
    If MySettings.LoginName = Nothing Then
        MySettings.LoginName = "name"
    ElseIf MySettings.LoginPassword = Nothing Then
        MySettings.LoginPassword = "password"
    End If
    If MySettings.LocationsList Is Nothing Then
        MySettings.LocationsList = New List(Of String)
        MySettings.LocationsList.Add("Location 1")
    End If
    bf.Serialize(ms, MySettings)
    Dim mySaveState As Byte() = ms.ToArray()
    File.WriteAllBytes(savepath, mySaveState)
End Sub