1
votes

I have a class that has a handful of public members that contain some data about the state of the current app. The framework I am using defines a few data structures that aren't marked as serializable - lets use Vector3 as an example.

When I try to serialize my programs data, I get an error - Vector3 is not marked as serializable.

[System.Serializable]
public class ProgramData
{
    public Vector3 test;
    public bool test2;

}

I can define my own serialization for this class to step around the issue -

[System.Serializable]
public class ProgramData : ISerializable
{
    public Vector3 test;
    public bool test2;

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("testx", test.x);
        info.AddValue("testy", test.y);
        info.AddValue("testz", test.z);
        info.AddValue("test2", test2);
    }

    protected ProgramData(SerializationInfo si,
    StreamingContext context)
    {
        test = new Vector3((float)si.GetDouble("testx"), (float)si.GetDouble("testy"), (float)si.GetDouble("testz"));
        test2 = si.GetBoolean("test2");
    }
}

This works fine, but it is a pain to maintain, because now I have to tell it how to serialize/deserialize the entire class - I have to maintain the GetObjectData and the protected construction methods as I extend my data class. This is impracticable.

Instead, I would like to tell my program how to deserialize 'Vector3's, and have it use those instructions whenever it encounters a Vector3.

1

1 Answers

0
votes

One possible approach would be to create a new class that is used as a wrapper for a Vector3 instance. This wrapper class, lets calls it Vector3W, is implemented as serializable and saves/restores the underlying Vector3 instance. Add some properties/methods to the wrapper that mimic the properties/methods of the underlying Vector3 and are implemented by simply calling onto that underlying instance. Then you can just replace each instance of Vector3 with Vector3W and know it will persist correctly.