[Serializable] public class MyViewModel : IEditableObject { [NonSerialized] private object[] _copy; public MyViewModel() { Name = string.Empty; } public int Age { get; set; } public string Name { get; set; } public void BeginEdit() { //take a copy of current state var members = FormatterServices.GetSerializableMembers(GetType()); _copy = FormatterServices.GetObjectData(this, members); } public void CancelEdit() { //roll back to copy var members = FormatterServices.GetSerializableMembers(GetType()); FormatterServices.PopulateObjectMembers(this, members, _copy); } public void EndEdit() { //discard copy _copy = null; } }
FormatterServices的方法比较有意思