【发布时间】:2014-07-29 05:05:14
【问题描述】:
我已经设置了这个空属性:
但是在将新的 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 可以)
但在this post(MemoryStream 的答案)的最后一个答案中,解释了一种将 ArrayList 的更改永久保存到 my.settings 的简单方法,然后在下一次应用程序运行时读取它。
答案似乎很好,但我对代码和执行步骤有点迷茫,所以有人可以解释那里解释的步骤,但请用人类可读的语言为我解释一下吗?
我已经验证 ArrayList 仍然在下一个应用程序运行中,是的,但我不确定我在做什么,因为如果 MemoryStream 包含旧的 ArrayList,那么我现在正在做的是分配 My .Settings.MRU 设置为包含更多 Arraylists 的 Arraylist,而不是包含 String() 的原始 ArrayList,无论如何在以这种方式保存设置后如何加载数组条目?。
这是我从那个答案中尝试过的:
' 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)
【问题讨论】:
-
我建议您使用文本文件或数据库来保存数据。
-
谢谢,我知道如何实现您评论过的替代方案(ini 文件或 xml 数据库),但我熟悉 My.Settings 的用法,我想在这种情况下保留它,因为这个应用程序确实不需要操作文本文件来存储/加载用户设置,因为我没有尝试设置用户可以通过编辑文件来决定其值的设置,我只是想设置一个 MRU环境。正如我所说,我熟悉 MY.Settings 界面,但这是我第一次遇到这种问题,我想修复它而不是避免它。感谢您的评论。
-
每个文件,也是一个数据库,任何人都可以更改。您可以选择隐藏路径,例如
AppData。 -
@Joiner 是的,我知道你是对的,但是使用 My.Settings 它已经在 AppData (Roaming) 文件夹中创建了一个文件,我们可以说“它对他的用户隐藏”避免了创建使用自定义对象(如我的 ArrayList 和所有可能受到威胁的对象)读取/写入配置文件的自定义实现。感谢您的评论!
-
如果您想使用 my.settings - 添加字符串键并将 ArrayList 序列化为字符串,例如使用 Xmlserializtion。然后将其存储在 My.Settings
标签: .net vb.net winforms visual-studio-2013 my.settings