简体   繁体   中英

Serialize C# object, want to deserialize to an interface

I want to send instruction objects between a server and a client. I want to be able to serialize an implementation of an interface and then, when I deserialize it, I want to deserialize it to the generic interface type (while it maintains the actual type it was serialized as).

I tried doing this with the default BinarySerializer but I encountered problems when sending the information across the wire.

I also tried using Protobuf to serialize but with Protobuf you must know the fully qualified type of the object you want to deserialize to. IE:

public interface IExample
{
     void foo();
}
public class Implementation : IExample
{
     void foo() { Console.WriteLine("This is an implementation!"); }
}

can only be deserialized with:

Serializer.Deserialize<Implementation>(stream); 

which defeats the point of polymorphism.

Is there a serialization library I can use where the caller of the deserialize method doesn't need to know the object's fully qualified type?

IE:

Implementation imp = new Implementation();
Stream inStream = Serialize(implementation);
IExample example = Deserialize(inStream);

example.foo();

This should print "This is an implementation!" to the console.

JSON is what I would recommend. Of course if you want to parse it as a type, you always need to know a type, but the JSON serializer is the best for what I think you need.

I would recommend using the DataContractJsonSerializer in System.Runtime.Serialization.Json as it is the most flexible in my experience.

Here is some additional helpful questions/articles about emitting and deserializing to types: when does DataContractJsonSerializer include the type information?

http://kashfarooq.wordpress.com/2011/01/31/creating-net-objects-from-json-using-datacontractjsonserializer/

You are wanting to walk on shifting sands, which can be hard to manage in strictly typed languages.

If you have an object, try the approach of using the as keyword:

var example = Desrialize(inStream) as IExample;
if (example != null)
    example.foo();

The method I would use though would be to create a particular base object and implement IExample on that base, then when deserializing any object that extends it you can still cast them as the base object or as IExample . Alternatively, consider whether the polymorphism should take place in the Deserialize() method, either by overloading or by using generics.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM