Question

CustomLineCap does not have the SerializableAttribute applied to it.

I want to add a property of this type to an object graph that is currently being serialized/deserialized with a BinaryFormatter.

I tried switching to XML serialization but it has a bunch of extra requirements and I don't want to fool with that esp. since it's not my code; it's some open source I downloaded.

If there's a way to get BinaryFormatter to ignore the property, that might work.

I'd rather subclass it; I just don't know if that will work either.

Was it helpful?

Solution

You aren't going to be able to serialize an instance of the CustomLineCap class directly. It derives from the MarshalByRefObject class, and while that's not an indicator that it can't be serialized, it's almost always the case.

The reason being that the MarshalByRefObject class is usually an indicator that the object that derives from it only has context in the application domain in which the instance lives. In this case, you the CustomLineCap instance is a GDI object which only has any meaning in the process that it lives in (it's tied explicitly to a handle).

That said, I'd recommend using the adapter pattern to create a wrapper that captures the properties of the CustomLineCap instance that you wish to serialize and then expose and serialize that.

This is generally the approach you'd want to take with any class that has a context that is tied to a specific domain that when serialized to be persisted outside of that domain, doesn't make sense anymore.

Note that subclassing won't work in this scenario either, in that applying the SerializableAttribute to your subclass means that all of the fields (even the private ones that you don't have access to) will be serialized, including any handles which only have context in the application domain they are created in.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top