在 .NET / C# 中克隆或使 MailMessage 不可变
我正在编写一个小型库,在其中编写一些接口,这些接口接受 MailMessage 对象并使用单个发送方法将类返回给我,该发送方法抽象了 MailMessage 的发送方式。我可以控制将进行实际发送的类,但我无法控制实施策略类。我想防止任何实施策略类更改 MailMessage。如何使 MailMessage(及其包含的集合)不可变或创建它的克隆?我在 MailMessage 本身上没有看到 .Clone 方法,就像在其他类上看到的那样。我是否必须新建一个新的 MailMessage 对象并对该新的 MailMessage 进行逐个属性设置?
请注意,我主要是一名 Java 人员,正在帮助客户使用 C# 2.0 代码,因此我对此类事情的 C# / .NET 习惯用法有点不熟悉。任何帮助表示赞赏。
I'm writing a small library where I'm writing some interfaces that takes a MailMessage object and returns a class back to me with a single send method that abstracts away how that MailMessage will be sent. I have control over the class that will do the actual sending, but I don't have control over the implementing strategy classes. I'd like to prevent any implementing strategy classes from altering the MailMessage. How can I make the MailMessage (and the collections it contains) immutable or create a clone of it? I don't see a .Clone method on MailMessage itself like I do on other classes. Will I have to result to new'ing up a new MailMessage object and doing a property-by-property set on that new MailMessage?
Note, I'm mostly a Java guy and am helping a client with C# 2.0 code, so I'm slightly unfamiliar with C# / .NET idioms for things like this. Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为对此没有快速的解决方案。
MailMessage
本质上是可变的,并且不适合克隆或序列化/反序列化。如果您需要确保没有人可以更改它,请不要缓存它,而是定义一个类来保存消息值的副本,并从此实例中创建新的MailMessage
实例。I don't think there is a quick solution for this. The
MailMessage
is inheritly mutable and isn't designed to be cloned or serialized/deserialized. If you need to make sure nobody can change it, don't cache it, but define a class that holds a copy of the values of the message and make newMailMessage
instances out of this instance.我知道这是一个老问题,但我最近不得不实现这个,所以这就是我所做的。 这是一个浅克隆,尽管需要做更多的工作,它可以变成一个深层克隆。
I know this is an old question, but I recently had to implement this so here's what I did. This is a shallow clone, though with a little more work it could be made into a deep clone.