据我了解,当我反序列化缺少这个新成员的旧版本的类时,我必须使用 [OptionalField] 属性在我的类的新版本中装饰一个新成员。
但是,在序列化类之后添加 InnerTranslator 属性时,下面的代码不会引发异常。我在 onDeserialization 方法中检查该属性是否为 null(这确认它没有被序列化),但我本以为代码会因此引发异常。[OptionalField] 属性本身是可选的吗?
class Program
{
static void Main(string[] args)
{
var listcol = new SortedList<string,string>
{
{"Estados Unidos", "United States"},
{"Canadá", "Canada"},
{"España", "Spain"}
};
var translator = new CountryTranslator(listcol);
using (var file_stream=new FileStream("translator.bin",FileMode.Open))
{
var formatter = new BinaryFormatter();
translator = formatter.Deserialize(file_stream) as CountryTranslator;
file_stream.Close();
}
Console.ReadLine();
}
}
[Serializable]
internal class CountryTranslator:IDeserializationCallback
{
public int Count { get; set; }
public CountryTranslator(SortedList<string,string> sorted_list)
{
this.country_list = sorted_list;
inner_translator = new List<string> {"one", "two"};
}
//[OptionalField]
private List<string> inner_translator;
public List<string> InnerTranslator
{
get { return inner_translator; }
set { inner_translator = value; }
}
private SortedList<string, string> country_list;
public void OnDeserialization(object sender)
{
Debug.Assert(inner_translator == null);
Count=country_list.Count;
}
}