As the documentation states, serializable classes must have a publicly accessible default constructor because they are instantiated. Abstract classes cannot be instantiated, however. That is the problem. The solution is easy: don't hardcode the type (using typeof in your example) in your serializable code. For one, one of the benefits (one could say, the "point") of using abstract classes is that you can use a generic to refer to multiple types without caring about the specific Type of the object. Instead, use o.GetType(). Remember that in OO, even though a variable might be declared as Test or Object (pulling examples from your code), they will still be instances of myObject or Test2. So, using o.GetType() will still return the Type for myObject (even if it were declared as an Object). If you use that in the constructor for the XmlSerializer, you shouldn't have any problems. This way, also, you don't hardcode that the serializer only accepts myObject. You will want to, however, use a condition or something before serializing to make sure that the object to be serialized is a Test derivative:
public void SaveTest(Test t)
{
// In this case, the CLR verifies that the object is of type Test
// (or a derivative) because the parameter above is a Test type.
XmlSerializer serializer = new XmlSerializer(t.GetType());
StreamWriter writer = new StreamWriter("test.xml");
serializer.Serialize(writer, t);
}
public void Save(object o)
{
// In this case, we should check to make sure that the object is
// a Test type. For brevity, well check and pass to SaveTest.
if (o is Test)
SaveTest(o as Test);
}
-----BEGIN GEEK CODE BLOCK----- Version: 3.21 GCS/G/MU d- s: a- C++++ UL@ P++(+++) L+(--) E--- W+++ N++ o+ K? w++++ O- M(+) V? PS-- PE Y++ PGP++ t++@ 5 X+++ R+@ tv+ b(-)>b++ DI++++ D+ G e++>+++ h---* r+++ y+++ -----END GEEK CODE BLOCK-----