Hi Jerry,
In the code below, notice that I used the Serializable attribute on the
types I want to serialize. Also, when I performed the serialization, I did
it on the A type, which was the root of the graph. Notice that after
serialization and deserialization that the B type that the A type references
is deserialized properly because the A type holds a reference to it.
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class A
{
private B _b;
public A (B b)
{
_b = b;
}
public B B
{
get { return _b; }
}
}
[Serializable]
class B
{
public string SomeVal;
}
class Test
{
static void Main()
{
B b = new B();
b.SomeVal = "I'm a B";
A a1 = new A(b);
MemoryStream memStr = null;
try
{
memStr = new MemoryStream();
BinaryFormatter binFmt = new BinaryFormatter();
binFmt.Serialize(memStr, a1);
memStr.Position = 0;
A a2 = (A)binFmt.Deserialize(memStr);
Console.WriteLine(a2.B.SomeVal);
}
finally
{
if (memStr != null)
{
memStr.Close();
}
}
Console.ReadLine();
}
}
Joe
--
http://www.csharp-station.com
Jerry said:
Hi,
I have a class like the following:
class A {
private B _b;
A (B b) {
_b = b;
}
...
public B B {
get { return _b; }
}
}
and:
class B {
...
}
How to serialize an A object and B object? Maybe another serialzied
object C has
a B reference also.
Jerry