此外,您可以使用 OnSerializingAttribute 和 OnSerializedAttribute 来设置字段。如示例所示,已设置的字段将保留其值。但是请注意,只有在 OnSerializing 事件期间设置了该字段时才会出现这种情况。OnSerialized 事件期间设置的字段将覆盖序列化值。
编辑:在这种情况下,如果字段等于 null 并在必要时实例化,您可以检查您的方法(用 OnSerialized 装饰)。如果有可能永远不会使用此字段并且可以推迟创建它,请考虑将有问题的字段隐藏在属性后面并延迟实例化它。
模型.cs:
using System;
using System.Runtime.Serialization;
namespace SerializationExample
{
[Serializable]
public class Model
{
public Model(){
A = new SomeClass();
}
[OptionalField]
public int value;
[OptionalField]
public SomeClass A;
[OptionalField]
public AnotherClass B;
[OnDeserializing]
void OnDeserializing(StreamingContext context)
{
B = new AnotherClass("Set during deserializing");
}
[OnDeserialized]
void OnDeserialized(StreamingContext context)
{
// Do sth. here after the object has been deserialized
}
public override string ToString()
{
return String.Format("A: {0}\nB: {1}", A, B);
}
}
[Serializable]
public class SomeClass
{
public string Value { get; set; }
public SomeClass()
{
Value = "Default";
}
public override string ToString()
{
return Value;
}
}
[Serializable]
public class AnotherClass
{
public string Value { get; private set; }
public AnotherClass(string v)
{
Value = v;
}
public override string ToString()
{
return Value;
}
}
}
程序.cs:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace SerializationExample
{
class Program
{
static void Main(string[] args)
{
string[] FileNames = new string[] {
@"model1.bin",
@"model2.bin"
};
Stream[] files = new Stream[] {
File.Create(FileNames[0]),
File.Create(FileNames[1])
};
BinaryFormatter bf = new BinaryFormatter();
Model m1 = new Model();
m1.B = new AnotherClass("Set in app");
m1.A.Value = "Set in app";
Model m2 = new Model();
Console.WriteLine("M1:\n{0}\n", m1);
Console.WriteLine("M2:\n{0}\n\n", m2);
bf.Serialize(files[0], m1);
bf.Serialize(files[1], m2);
foreach (var f in files)
f.Seek(0, SeekOrigin.Begin);
m1 = null;
m2 = null;
m1 = (Model)bf.Deserialize(files[0]);
m2 = (Model)bf.Deserialize(files[1]);
Console.WriteLine("M1:\n{0}\n", m1);
Console.WriteLine("M2:\n{0}\n\n", m2);
foreach (var f in files)
f.Close();
}
}
}
输出:
M1:
A: Set in app
B: Set in app
M2:
A: Default
B:
M1:
A: Set in app
B: Set in app
M2:
A: Default
B: Set during deserializing