.Net Binary Serialization inheritance
In a C# Context, I have a Class B which is marked as Serializable and who's inheriti开发者_如何学Gong 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?
Try using a serialization surrogate. Nice article by Jeff Richter
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).
精彩评论