问题描述
本身似乎很直接。我正在考虑与维基百科的例子一样实现,但在我做之前,是否有C#的任何语言特性使其更容易实现或使用?
The Memento Pattern itself seems pretty straight forward. I'm considering implementing the same as the wikipedia example, but before I do are there any language features of C# that make it easier to implement or use?
推荐答案
一个明显的特征是泛型,实现一个通用的记事本将允许你将它用于任何你想要的对象。
One obvious feature would be generics, implementing an generic memento will allow you to use it for any object you want.
您将看到的许多示例将使用一个字符串(包括当前在此问题的回复中的所有内容)作为状态,这是一个问题,因为它是少数几种类型之一在.NET中,这是不可变的。
Many examples that you will see will use a string (including all those currently among the replies to this question) as state which is a problem since it's one of the few types in .NET which are immutable.
当处理可变对象(像使用setter属性的任何引用类型)时,您必须记住,当您保存纪念品时需要创建一个对象的深层拷贝。否则每当你改变你的原始对象,你会改变你的纪念品。
When dealing with mutable objects (like any reference type with a setter-property) you have to remember though that when you save the memento you need to create a deepcopy of the object. Otherwise whenever you change your original object you will change your memento.
您可以使用像或,因为它们不要求您标记对象具有类似正常的.net序列化机制的可序列化属性。
You could do this by using a serializer like protobuf-net or json.net since they don't require you to mark your objects with serializable attribute like the normal .net serialization mechanism does.
Codeproject有关于通用化学实现的文章很少,但是它们倾向于跳过deepcopy部分:
Codeproject have few articles about generic memento implementations, but they tend to skip the deepcopy part:
这篇关于如何在C#4中实现Memento模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!