Using .NET XmlSerializer with get properties and setter functions
Posted
by brone
on Stack Overflow
See other posts from Stack Overflow
or by brone
Published on 2010-03-15T19:40:56Z
Indexed on
2010/03/17
17:51 UTC
Read the original article
Hit count: 396
I'm trying to use XmlSerializer
from C# to save out a class that has some values that are read by properties (the code being just a simple retrieval of field value) but set by setter functions (since there is a delegate called if the value changes).
What I'm currently doing is this sort of thing. The intended use is to use the InT
property to read the value, and use SetInT
to set it. Setting it has side-effects, so a method is more appropriate than a property here. XmlSerializationOnly_InT
exists solely for the benefit of the XmlSerializer
(hence the name), and shouldn't be used by normal code.
class X
{
public double InT
{
get { return _inT; }
}
public void SetInT(double newInT)
{
if (newInT != _inT)
{
_inT = newInT;
Changed();//includes delegate call; potentially expensive
}
}
private double _inT;
// not called by normal code, as the property set is not just a simple
// field set or two.
[XmlElement(ElementName = "InT")]
public double XmlSerializationOnly_InT
{
get { return InT; }
set { SetInT(value); }
}
}
This works, it's easy enough to do, and the XML file looks like you'd expect. It's manual labour though, and a bit ugly, so I'm only somewhat satisfied. What I'd really like is to be able to tell the XML serialization to read the value using the property, and set it using the setter function. Then I wouldn't need XmlSerializationOnly_InT
at all.
I seem to be following standard practise by distinguishing between property sets and setter functions in this way, so I'm sure I'm not the only person to have encountered this (though google suggests I might be). What have others done in this situation? Is there some easy way to persuade the XmlSerializer
to handle this sort of thing better? If not, is there perhaps some other easy way to do it?
© Stack Overflow or respective owner