How do I store an array of a particular type into my settings file?

孤街浪徒 提交于 2020-01-01 17:10:21

问题


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.


回答1:


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:

    [global::System.Configuration.UserScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    public List<Link> Links
    {
        get {
            return ((List<Link>)(this["Links"]));
        }
        set {
            this["Links"] = value;
        }
    }

I had to make these changes in the Settings.Designer.cs and not from the designer.




回答2:


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.



来源:https://stackoverflow.com/questions/2761924/how-do-i-store-an-array-of-a-particular-type-into-my-settings-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!