Self-deserialising object

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Paul E Collins

    #1

    Self-deserialising object

    I'm using XmlSerializer to write objects of my own class to disk. I'd prefer
    to do this from inside the class, so that I can just write
    Settings.Load(. ..) and Settings.Save(. ..).

    The code I tried is below. However, the Load method fails because the 'this'
    object is read-only.

    Is there a simple way for an object to deserialise itself, or am I better
    off doing it from outside the class?

    public void Save(string strFilename)
    {
    XmlSerializer x = new XmlSerializer(t ypeof(MyObject) );
    using (TextWriter writer = new StreamWriter(st rFilename))
    {
    x.Serialize(wri ter, settings);
    writer.Close();
    }
    }

    public void Load(string strFilename)
    {
    XmlSerializer x = new XmlSerializer(t ypeof(MyObject) );
    using (TextReader reader = new StreamReader(st rFilename))
    {
    this = (MyObject) x.Deserialize(r eader);
    reader.Close();
    }
    }

    P.

    --



  • Jon Skeet

    #2
    Re: Self-deserialising object

    (Apologies if this comes out twice - if it does, ignore the other
    post.)

    Paul E Collins <find_my_real_a ddress@CL4.org> wrote:[color=blue]
    > I'm using XmlSerializer to write objects of my own class to disk. I'd prefer
    > to do this from inside the class, so that I can just write
    > Settings.Load(. ..) and Settings.Save(. ..).
    >
    > The code I tried is below. However, the Load method fails because the 'this'
    > object is read-only.
    >
    > Is there a simple way for an object to deserialise itself, or am I better
    > off doing it from outside the class?[/color]

    It makes more sense to have Load as a static method which returns a new
    instance of the class.

    --
    Jon Skeet - <skeet@pobox.co m>
    Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

    If replying to the group, please do not mail me too

    Comment

    Working...