rakesh
rakesh

Reputation: 612

How do I serialize delegates in my WP7 application

I am building an application for WP7. And I am working on the tombstoning part of my application.

And I have got a class such that

namespace packetq{
    public class Packet{
        int x;
        //some other information;
    }
}  

namespace packetq{
    public class PacketState{
        Packet A;
        func<Packet,Packet>   handler;
    }
}

Now I have a class which Instantiates Packet object and assigns a handler to it.

when my application tombstones. I need to store this PacketState object so that When i restore it back I should be able to work on that Packet And I should be able to handle that Packet using that Handler.

So I need to serialize and persist that handler.

I read few articles it says that persistence and serialization could be done using Expression tree. But that way is really cumbersome.

Please suggest some other way to do it.

Upvotes: 2

Views: 172

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063413

Since BinaryFormatter is not available, my advice would be: use a class instance (subclass of a common base-type) and a polymorphic method instead, perhaps using a decorator pattern. I don't know which serializer you are planning to use, but most can handle inheritance as long as the sub-types are known in advance.

So instead of a Func<Packet,Packet> you might have a PacketHandler base-class with a virtual method that accepts and returns Packet

To elaborate:

[DataContract, KnownType(typeof(EchoPacketHandler)]
public class PacketHandler {
    public virtual Packet Handle(Packet packet) { throw new NotSupportedException(); }
}
[DataContract]
public class EchoPacketHandler : PacketHandler {
    public override Packet Handle(Packet packet) { return packet; }
}

But add more subclasses, and state via [DataMember] as needed.

Upvotes: 2

Related Questions