In a C# Context, I have a Class B which is marked as Serializable and who's inheriting form a Class A who's not marked as this. Can i find a way to serialize instance of B without marking A as serializable?
A:
I think if you do custom serialization this should work - i.e. implement ISerializable
. Not a nice option, though:
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
class A {
public int Foo { get; set; }
}
[Serializable]
class B : A, ISerializable {
public string Bar { get; set; }
public B() { }
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
info.AddValue("Foo", Foo);
info.AddValue("Bar", Bar);
}
private B(SerializationInfo info, StreamingContext context) {
Foo = info.GetInt32("Foo");
Bar = info.GetString("Bar");
}
}
static class Program {
static void Main() {
BinaryFormatter bf = new BinaryFormatter();
B b = new B { Foo = 123, Bar = "abc" }, clone;
using (MemoryStream ms = new MemoryStream()) {
bf.Serialize(ms, b);
ms.Position = 0;
clone = (B)bf.Deserialize(ms);
}
Console.WriteLine(clone.Foo);
Console.WriteLine(clone.Bar);
}
}
Do you just want to store the data? I can also think of a way to do this using protobuf-net (rather than BinaryFormatter
, which I assume you are using).
Marc Gravell
2009-12-16 12:55:39
Thanks for your answer. Yes, exactely, i'am using BynaryFormatter. The need is to store the object's data. About protobuf-net, what's the advantages of using it instead of BinaryFormatter? is there any examples?
2009-12-16 13:07:21
a: faster and smaller (http://code.google.com/p/protobuf-net/wiki/Performance) b: platform/language independent (http://code.google.com/p/protobuf/wiki/ThirdPartyAddOns) c: not metadata specific (can rename fields, move/rename types, etc: http://marcgravell.blogspot.com/2009/03/obfuscation-serialization-and.html). Brief intro: http://code.google.com/p/protobuf-net/wiki/GettingStarted
Marc Gravell
2009-12-16 13:11:48
Note that the intro doesn't cover inheritance, and the inheritance support in protobuf-net is a customisation and won't map *directly* to Java/C++/etc: they'll see the data, but not as inheritance (hey, I didn't design the wire format...)
Marc Gravell
2009-12-16 13:12:47
A small potential gotcha: You may want to mark the base class A as sealed if possible in case someone later on implemented a custom serialiser on it. This would then break the serialisation on B.
Andrew
2009-12-16 13:22:54
I think you mean B sealed?
Marc Gravell
2009-12-17 08:33:56