开发者

Is it possible to deserialize to the current class?

开发者 https://www.devze.com 2023-01-06 04:48 出处:网络
I have a settings class that I want to be able to serialize and deserialize to save and load settings to a file.

I have a settings class that I want to be able to serialize and deserialize to save and load settings to a file.

With hindsight, I'd have designed my whole app to create an instance of settings when needed. As it is, my settings are persistent (mimicking the default application settings behaviour). Given my current architecture, I can do the following:

public void Save()
{
    Stream stream = File.Open("settings_test.xml", FileMode.Create);
    XmlSerializer x = new XmlSerializer(this.GetType());
    x.Serialize(stream, this);
}

Obviously, I can't do this:

public void Load()
{
    Stream stream = File.Open("settings_test.xml", FileMode.Open);
    XmlSerializer x = new XmlSerializer(this.GetType());
    this = x.Deserialize(开发者_C百科stream);
}

But is there a way to update all the public properties of the current class to match those of the deserialized object?

(I suppose the more general questions is: "Is there an efficient way to update one class based on the contents of another?")


I would make the settings class an singelton and have a static Instance to it then you could call load and save on that instance

public class MySettings
{
    private static MySettings _instance;
    public static MySettings Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new MySettings();
                // maby call Load();
            }
            return _instance;
        }
    }
    private MySettings()
    {  
        //set default values
    }

    public void Load()
    {
        Stream stream = File.Open("settings_test.xml", FileMode.Open);
        XmlSerializer x = new XmlSerializer(this.GetType());
        _instance = (MySettings)x.Deserialize(stream);
    }

    public void Save()
    { 
        Stream stream = File.Open("settings_test.xml", FileMode.Create);
        XmlSerializer x = new XmlSerializer(this.GetType());
        x.Serialize(stream, _instance);
    }
}


I would use a static method

MyClass myclass = MyClass.Load("settings.xml")

Otherwise you can achive that with reflection.

Found this example via google: http://www.csharp-examples.net/reflection-examples/


Another option is AutoMapper.

0

精彩评论

暂无评论...
验证码 换一张
取 消