我设置了这个空属性:
但是在为属性分配一个新的ArrayList对象后,该属性在每次应用程序执行中始终为空。
在MyBase.Load事件的处理程序中,我调用了这个方法,只是为了测试这个问题:
sub blahblah handles mybase.load
me.CheckRecentFiles
end sub
Private Sub CheckRecentFiles()
Try
' This throws an object not referenced exception 'cause always is empty.
MsgBox(My.Settings.RecentFiles.Count)
Catch ex As Exception
MsgBox(ex.Message)
End Try
' Just for testing, if the collection is empty then I instance a new ArrayList
' and I assign it to the property and I save it and exit from the application.
' But even doing this the property is always empty in the next execution.
If My.Settings.RecentFiles Is Nothing Then
My.Settings.RecentFiles = New ArrayList
My.Settings.RecentFiles.Add({"test-Item1", "test-Item2", "Test-Item3"})
My.Settings.Save()
Application.Exit()
End If
End Sub
正如您在上面的代码中看到的那样,我正在为一个新的 ArrayList 分配一个条目,但更改仅在该应用程序执行期间生效,如果我退出应用程序,则该属性再次变为空。
当然,我也检查了这个选项:
但无论如何这是不必要的,因为我在代码中手动保存设置,所以......
为什么会这样?。
我该如何解决这个问题?
更新:
我进行了调查,似乎这是一个已知问题,即 my.settings 无法保存数组、ArrayLists 和任何通用集合(类型)(但另一方面,StringCollection 可以)
但是在这篇文章的最后一个答案(MemoryStream 答案)中,解释了一种将 ArrayList 的更改永久保存到 my.settings 的简单方法,然后在下一次应用程序运行时读取它。
答案似乎很好,但是我对代码和继续执行的步骤有点迷茫,所以有人可以解释那里解释的步骤,但请用一种人类可读的语言来解释我吗?
我已经验证 ArrayList 仍然在下一个应用程序运行中,是的,但我不确定我在做什么,因为如果 MemoryStream 包含旧的 ArrayList,那么我现在正在做的是分配 My.Settings。 MRU 设置为 Arraylist,其中包含更多内容,Arraylists
而不是包含 ? 的原始 ArrayList,String()
无论如何在以这种方式保存设置后如何加载数组条目?
这是我从那个答案中尝试过的:
' Create the ArrayList
Dim tmpArrayList = New System.Collections.ArrayList
tmpArrayList.Add({"test-Item1-1", "test-Item1-2", "Test-Item1-3"})
tmpArrayList.Add({"test-Item2-1", "test-Item2-2", "Test-Item2-3"})
' Serialize the arraylist entries:
Dim formatter As Runtime.Serialization.IFormatter =
New Runtime.Serialization.Formatters.Binary.BinaryFormatter
Dim ms1 As New IO.MemoryStream
formatter.Serialize(ms1, tmpArrayList)
' Save the ArrayList
My.Settings.MRU = New ArrayList(ms1.ToArray) ' I think it hould be like that?
' Load the ArrayList contained in My.Settings.MRU (no idea)