如何将特定类型的数组存储到我的设置文件中?
由于某种原因,我似乎无法将我的类的数组存储到设置中。代码如下:
var newLink = new Link();
Properties.Settings.Default.Links = new ArrayList();
Properties.Settings.Default.Links.Add(newLink);
Properties.Settings.Default.Save();
在我的 Settings.Designer.cs 中,我将字段指定为数组列表:
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::System.Collections.ArrayList Links {
get {
return ((global::System.Collections.ArrayList)(this["Links"]));
}
set {
this["Links"] = value;
}
}
出于某种原因,即使 Link 类是可序列化的并且我已经对其进行了测试,它也不会保存任何数据。
For some reason, I can't seem to store an array of my class into the settings. Here's the code:
var newLink = new Link();
Properties.Settings.Default.Links = new ArrayList();
Properties.Settings.Default.Links.Add(newLink);
Properties.Settings.Default.Save();
In my Settings.Designer.cs I specified the field to be an array list:
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::System.Collections.ArrayList Links {
get {
return ((global::System.Collections.ArrayList)(this["Links"]));
}
set {
this["Links"] = value;
}
}
For some reason, it won't save any of the data even though the Link class is serializable and I've tested it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我找到了问题的根源。仅仅使用普通数组是不够的。经过思考,反序列化器不知道将数组项反序列化为什么类型。我没有看到数组需要强类型。设计器让我愚蠢地相信它是一个普通的通用数组:
我必须在 Settings.Designer.cs 中进行这些更改,而不是从设计器那里进行。
I found the source of the problem. Simply using a plain Array won't cut it. After thinking about it, the deserializer wouldn't know what type to deserialize the array items to. I failed to see that the array required strong typing. The designer lead me to foolishly believe it was a plain generic array:
I had to make these changes in the Settings.Designer.cs and not from the designer.
确保您的 Link 类可以正确地进行 XML 序列化,或者具有字符串类型转换器(在使用 application.settings 文件时这是首选)。
我假设您的类型中的某些内容不会转换为 XML 序列化格式。并且您的 user.config 显示它没有任何可用的字符串类型转换器。
Make sure that your Link class is either correctly XML-serializable or that it has a typeconverter to string (which is preferred when using application.settings files).
I'd assume that something in your types will not transform into the XML-serialization format. And your user.config shows that it doesn't have any string typeconverter available.