B
Beorne
I have to use XmlSerializer to serialize a class and I've found big
problems serializing properties and indexers.
I assumed that if you serialize a class with public properties (or an
indexers) containing a field, even private, the serialization process
would serialize that field too assuming it is needed to that public
property. This is not the case ...
For example I want to serialize the following class:
[Serializable]
public class Test
{
readonly int[] a; // same results with private
readonly int b; // same results with private
public Test(int[] v1, int b)
{
a = v1;
b = v2;
}
public Test() : this(new int[] {10, 10}, 50) { }
public int this[int i]
{
get { return a; }
set { a = value; }
}
public bool b100
{
get { return b > 100; }
set { }
}
}
I serialize it after constructing it with
Test test = new Test(new int[] { 30, 30 }, 200);
the resulting xml contains:
<test>
<b100>true</b100>
</test>
that is not useful in any way.
If I change the readonly (or private, it is the same) members class to
public the resulting xml contains:
<test>
<a>
<int>30</int>
<int>30</int>
</a>
<b>200</b>
<b100>true</b100>
</test>
That is what I want.
Finally the question: how can I serialize my classes without having to
make all fields public and without using simple expose properties like
public int A
{
get { return a; }
set { a = value; }
}
???
Thank you,
Matteo
problems serializing properties and indexers.
I assumed that if you serialize a class with public properties (or an
indexers) containing a field, even private, the serialization process
would serialize that field too assuming it is needed to that public
property. This is not the case ...
For example I want to serialize the following class:
[Serializable]
public class Test
{
readonly int[] a; // same results with private
readonly int b; // same results with private
public Test(int[] v1, int b)
{
a = v1;
b = v2;
}
public Test() : this(new int[] {10, 10}, 50) { }
public int this[int i]
{
get { return a; }
set { a = value; }
}
public bool b100
{
get { return b > 100; }
set { }
}
}
I serialize it after constructing it with
Test test = new Test(new int[] { 30, 30 }, 200);
the resulting xml contains:
<test>
<b100>true</b100>
</test>
that is not useful in any way.
If I change the readonly (or private, it is the same) members class to
public the resulting xml contains:
<test>
<a>
<int>30</int>
<int>30</int>
</a>
<b>200</b>
<b100>true</b100>
</test>
That is what I want.
Finally the question: how can I serialize my classes without having to
make all fields public and without using simple expose properties like
public int A
{
get { return a; }
set { a = value; }
}
???
Thank you,
Matteo