How can I deserialize an interface type?

I serialize a class that includes the Model property as an IModel , but when I try to deserialize it, I get the following exception:

 System.Runtime.Serialization.SerializationException: Type 'MYN.IModel' in Assembly 'MYN.Defs, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable. 

This is binary serialization. Model marked as serializable. Obviously IModel is not.

So what is the solution, what am I doing wrong? Why is he trying to serialize or deserialize an interface?

PS The interface did not receive Enum.

+4
source share
4 answers

It makes sense to get this error, since the IModel property can refer to different classes, and there is no guarantee that all of them are Serializable.


OK, I tried, and we have:

Test system error, it works on my computer.


 interface IFoo { } [Serializable] class CFoo : IFoo { } [Serializable] class Bar { public IFoo Foo { get; set; } } 

Both Bar Serializes and Deserializes are excellent.

 Bar b = new Bar(); b.Foo = new CFoo(); using (var s = new System.IO.MemoryStream()) { var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(s, b); s.Position = 0; b = (Bar)bf.Deserialize(s); Console.WriteLine("OK"); } 

So what is different from your IModel and Model ?

+5
source

I suspect this because during deserialization, it initiates a new instance of the class and then copies the data into it. It cannot create a new interface, so deserialization cannot be completed. That's why you need a constructor that takes no arguments for serialization.

Not sure about the solution, I have never worked with this. I probably override the class and inherit the property from a specific type, and then serialize it.

+3
source

You probably need to implicitly expand these properties in your class:

instead of IModel.Model add property

 public MyClass Model 
0
source

I am sure that you cannot serialize / deserialize interfaces, but only instances of classes. I canโ€™t find the documentation supporting this, but I remember trying to do the same without any success.

You can try using an abstract base class instead of an interface, but I have not tried this.

0
source

All Articles