拷贝构造函数与克隆() [英] Copy constructor versus Clone()

查看:154
本文介绍了拷贝构造函数与克隆()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,什么是添加(深)复制功能,一类preferred方式?每个人都应该实行的拷贝构造函数,或者从 ICloneable 而得到贯彻克隆()的方法?

In C#, what is the preferred way to add (deep) copy functionality to a class? Should one implement the copy constructor, or rather derive from ICloneable and implement the Clone() method?

备注:我写括号内深,因为我认为这是无关紧要的。显然其他人并不同意,所以我就问<一个href=\"http://stackoverflow.com/questions/3350725/does-a-copy-constructor-operator-function-need-to-make-clear-which-copy-variant-i\">whether拷贝构造函数/操作/函数需要明确它复制变异它实现。

Remark: I wrote "deep" within brackets because I thought it was irrelevant. Apparently others disagree, so I asked whether a copy constructor/operator/function needs to make clear which copy variant it implements.

推荐答案

您不应该从 ICloneable 派生。

原因是,当微软设计的.NET Framework中他们从来没有规定是否克隆()的方法 ICloneable 应该是一个深或浅的克隆,从而接口语义上破为来电者不知道是否来电会深或浅克隆的对象。

The reason is that when Microsoft designed the .net framework they never specified whether the Clone() method on ICloneable should be a deep or shallow clone, thus the interface is semantically broken as your callers won't know whether the call will deep or shallow clone the object.

相反,你应该定义你自己的 IDeepCloneable (和 IShallowCloneable )使用 DeepClone接口()(和 ShallowClone())的方法。

Instead, you should define your own IDeepCloneable (and IShallowCloneable) interfaces with DeepClone() (and ShallowClone()) methods.

您可以定义两个接口,其中一个泛型参数来支持强类型的克隆和一个没有继续当你与不同类型的可复制对象的集合致力于为弱类型的克隆能力:

You can define two interfaces, one with a generic parameter to support strongly typed cloning and one without to keep the weakly typed cloning ability for when you are working with collections of different types of cloneable objects:

public interface IDeepCloneable
{
    object DeepClone();
}
public interface IDeepCloneable<T> : IDeepCloneable
{
    T DeepClone();
}

,你会再实现这样的:

Which you would then implement like this:

public class SampleClass : IDeepCloneable<SampleClass>
{
    public SampleClass DeepClone()
    {
        // Deep clone your object
        return ...;
    }
    object IDeepCloneable.DeepClone()   
    {
        return this.DeepClone();
    }
}

一般来说,我preFER使用说明,而不是它保持的意图非常明确拷贝构造函数的接口。复制构造可能会被认为是一个深刻的克隆,但它肯定不是尽可能多的明确意图是用IDeepClonable接口。

Generally I prefer to use the interfaces described as opposed to a copy constructor it keeps the intent very clear. A copy constructor would probably be assumed to be a deep clone, but it's certainly not as much of a clear intent as using an IDeepClonable interface.

这是.NET <一个讨论href=\"http://www.amazon.co.uk/Framework-Design-Guidelines-Conventions-Development/dp/0321545613/ref=sr_1_1?ie=UTF8&s=books&qid=1280246424&sr=8-1\">Framework设计指南和布拉德·艾布拉姆斯'博客

<子>(我想,如果你正在写的应用程序(而不是一个框架/库),所以你可以确保没有人团队之外将致电code,它并不那么重要多,你可以指定deepclone到.NET ICloneable接口的语义,但是你要确保这是有据可查的,并同时在团队内部的理解。我个人会坚持指导原则框架。)

这篇关于拷贝构造函数与克隆()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆