简体   繁体   中英

Why can't I serialize an object with a struct in it?

I have an "options" object that I'm trying to save to Settings

public class MainWindow
{
    public MyOptions MyOptions => (MyOptions)DataContext;

    public MainWindow()
    {
        InitializeComponent();

        DataContext = Settings.Default.MyOptions ?? new MyOptions();
    }

    private void OnOptionsChanged(object sender, PropertyChangedEventArgs e)
    {
        Settings.Default.MyOptions = MyOptions;
        Settings.Default.Save();
    }

    // etc.
}

MyOptions contains (among other things) a struct-value

public class MyOptions
{
    private MyStruct _myStruct;

    public MyOptions()
    {
        _myStruct = someDefaultValue;
    }

    // etc.
}

MyStruct contains only a single int:

public struct MyStruct
{
    private readonly int _someValue;
    public MyStruct(int someValue)
    {
        _someValue = someValue;
    }

    // etc.
}

When I make the call to Settings.Default.MyOptions = MyOptions; , all the values are set correctly, including myStruct .

However, when I restart the program and load the options with DataContext = Settings.Default.MyOptions , all the values are correctly loaded except for _myStruct, which defaults to 0 !

According to everything I've read, this code should work. I've tried adding the [Serializable] attribute to both the class/struct, as well as implementing ISerializable (which I shouldn't have to do), but neither helped. What am I missing?

Settings are serialized as XML, which has a limitation of excluding readonly members.

Removing readonly qualifier should fix this problem:

public struct MyStruct {
    internal int _someValue;
    public MyStruct(int someValue) {
        _someValue = someValue;
    }
}

Try this struct, in my test case it serialized right way:

public struct MyStruct
{
    public int SomeValue { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM