65.9K
CodeProject 正在变化。 阅读更多。
Home

使用泛型在 C# 中进行对象克隆

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.76/5 (14投票s)

2008年4月21日

CPOL
viewsIcon

52770

downloadIcon

377

这个工具使用泛型创建类的新实例。

引言

在一个项目中,我遇到了一种需要克隆对象的情况,不幸的是,C# 并没有提供这样的工具,或者说也许有,但我不知道!无论如何,我首先在 MSDN 上查找 ICloneable 接口……然后我发现了一些有趣的文章,比如这篇:C# 中对象克隆的基础类然而,我最终决定使用泛型和 XmlSerializer 编写我自己的克隆类! CloneManager 是一个简单的类,可以创建任何类的实例。 此外,您的类不需要任何属性装饰!

使用代码

您需要做的就是添加对 CloneManager 项目的引用,并在您的源代码中创建该类的实例,如下所示。

代码示例

  //Create an instance of clone manager
  IClone cloneManager = new CloneManager();

  MyClass newInstance = cloneManager.Clone(instance);

实现

CloneManager 实现了 IClone 接口,该接口只公开一个方法。 Clone 方法简单地将实例序列化到内存流中,然后使用 XmlSerializer 将该流反序列化为对象的新实例,并将其返回给调用者。

    
public interface IClone 
{ 
    T Clone(T instance) where T : class; 
}



using System;
using System.Xml.Serialization;
using System.IO;

namespace Demo.Clone
{
    public class CloneManager:IClone
    {
        /// Clones the specified instance. 
        /// Returns a new instance of an object.
        T IClone.Clone(T instance){
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            MemoryStream stream = new MemoryStream();
            serializer.Serialize(stream, instance);
            stream.Seek(0, SeekOrigin.Begin);
            return serializer.Deserialize(stream) as T;
        }
    }
}



祝您编码愉快!

© . All rights reserved.