Reputation: 196741
I have a class that I have serialized to disk on local users machines. I need to refactor this class and I changed all objects (anything except enums, string, numbers) to interfaces. Underneath it is still the same concrete class. my concern is breaking existing users persistance
From:
public class Foo
{
public double Count;
public State MyState;
}
To
public class IFoo
{
public double Count;
public IState MyState;
}
but now I am getting errors from the serialization code that says "can't serialize because its an interface"
the error states:
"There was an error reflecting type 'Foo'." "Cannot serialize member 'Foo.My' of type 'IState', see inner exception for more details."
what is the best way around this?
Upvotes: 2
Views: 904
Reputation:
Consider having your IState
interface inherit from ISerializable
:
public interface IState : ISerializable
Read up on ISerializable
first. It adds a few complications to the matter.
Upvotes: 0
Reputation: 45422
You cannot serialize interfaces because the amount of types that can implement the interface is infinite and the serializer does not know what concrete type it is.
class A : IFoo {}
class B : IFoo {}
class C : IFoo {}
//snip//
IFoo f = new A();
f = new B();
f = new C();
You must specify if you are serializing A,B or C.
Another way to think of it is when deserializing to IFoo, how would you know which to create ... A, B or C .. etc?
Upvotes: 2
Reputation: 5374
I think you will have to handle serialization explicitly by implementing ISerializable. Think about how deserialization can determine what concrete class to use for IState. It does not know. That's why you would need to handle serialization on your own.
Upvotes: 0