我做了一个简单的小项目,以便在更大的项目中重现该问题。
我有3个类继承自ModelBase
public class Contact : ModelBase
{
[IncludeInSerialization]
public string FirstName { get; set; }
[IncludeInSerialization]
public string LastName { get; set; }
[IncludeInSerialization]
public DateTime DateOfBirth { get; set; }
[IncludeInSerialization]
public string PhoneNumber { get; set; }
[IncludeInSerialization]
public string Email { get; set; }
[IncludeInSerialization]
public ICollection<Address> Addresses { get; set; }
}
public class Lookup : ModelBase
{
[IncludeInSerialization]
public string Value { get; set; }
[IncludeInSerialization]
public string Group { get; set; }
}
public class Address : ModelBase
{
[IncludeInSerialization]
public Lookup Country { get; set; }
[IncludeInSerialization]
public Lookup StateOrTerritory { get; set; }
[IncludeInSerialization]
public string AddressText { get; set; }
public override string ToString()
{
return $"{AddressText}\r\n{StateOrTerritory?.Value},{Country?.Value}";
}
}
和主程序
class Program
{
static void Main(string[] args)
{
Contact customer = new Contact();
customer.FirstName = "Sam";
customer.LastName = "Smith";
customer.DateOfBirth = DateTime.Now.AddYears(-30);
customer.Addresses = new HashSet<Address>();
Lookup australia = new Lookup {Group = "Countries", Value = "Australia"};
Lookup NSW = new Lookup {Group = "StatesAndTerritories", Value = "NSW"};
Address firstAddress = new Address();
firstAddress.Country = australia;
firstAddress.StateOrTerritory = NSW;
firstAddress.AddressText = "1/1 A street, Sydney";
Address secondAddress = new Address();
secondAddress.Country = australia;
secondAddress.StateOrTerritory = NSW;
secondAddress.AddressText = "2/2 Another street, Sydney";
customer.Addresses.Add(firstAddress);
customer.Addresses.Add(secondAddress);
((IEditableObject)customer).BeginEdit();
Console.WriteLine("Addresses Before:");
Console.WriteLine();
foreach (Address address in customer.Addresses)
{
Console.WriteLine(address.ToString());
Console.WriteLine();
}
((IEditableObject)customer).CancelEdit();
Console.WriteLine("--------------------");
Console.WriteLine();
Console.WriteLine("Addresses After:");
Console.WriteLine();
foreach (Address address in customer.Addresses)
{
Console.WriteLine(address.ToString());
Console.WriteLine();
}
Console.Read();
}
}
反序列化前后,运行程序会为Addresses
产生不同的结果。
在第一次打印之前,请注意调用BeginEdit
会触发序列化,而在第二次打印之前请注意对CancelEdit
的调用会触发反序列化时间。
有人对正在发生的事情有见识吗?
文件:https://github.com/3m3sd1/Testing_Catel_Serialization/tree/master