Good day, Niners!
In .NET, if a field is dynamically generated once upon object ctor, how to ensure it has the same value after the process of Binary serialization and deserialization?
Test code as follows:
[Serializable()]
class FooException : ApplicationException
{
private int _errorNumber = 0;
public int ErrorNumber
{
get { return _errorNumber; }
internal set { _errorNumber = value; }
}
private static Random RDM = new Random();
private void initialize()
{
if (this._errorNumber == 0)
{
this._errorNumber = RDM.Next(50000, 100000);
}
}
public FooException()
: base()
{
initialize();
}
public FooException(string message)
: base(message)
{
initialize();
}
public FooException(string message, Exception exception)
: base(message, exception)
{
initialize();
}
protected FooException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
//maybe need some magic code here
}
static void Main(string[] args)
{
FooException ex = new FooException();
//i.e. ex.ErrorNumber = 1234;
Console.WriteLine(ex.ErrorNumber);
Console.WriteLine("-> Serialize / Deserialize");
string path = serialize(ex);
object o = deserialize(path);
ex = (FooException)o;
//PROBLEM: how to make sure ex.ErrorNumber has the same value 1234 as before serialization??
Console.WriteLine(ex.ErrorNumber);
Console.WriteLine("-> End of Serialize / Deserialize");
Console.ReadLine();
}
static string serialize(object o)
{
BinaryFormatter bf = new BinaryFormatter();
string path = Path.Combine(Environment.CurrentDirectory, "ObjectGraph.dat");
using (FileStream fs = File.Create(path))
{
bf.Serialize(fs, o);
return path;
}
}
static object deserialize(string path)
{
BinaryFormatter bf = new BinaryFormatter();
using (FileStream fs = File.OpenRead(path))
{
object o = bf.Deserialize(fs);
return o;
}
}
}
Thanks in advance!
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.