实现深拷贝的一种方法

声明接口:
    

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


建立CloneManager类实现接口:

public class CloneManager:IClone
    
{
        
/// <summary>
        
/// Clones the specified instance.
        
/// </summary>
        
/// <typeparam name="T"></typeparam>
        
/// <param name="instance">The instance.</param>
        
/// <returns>A new instance of an object.</returns>

        T IClone.Clone<T>(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;
        }

    }


实际应用代码:

class Program
    
{
        
static void Main(string[] args)
        
{
            IClone clone 
= new CloneManager.CloneManager();
            AA ta 
= new AA();
            ta.aa 
= 123;
            ta.bb 
= 234;
            AA tb 
= clone.Clone<AA>(ta);
            ta.aa 
= 999;
            ta.bb 
= 888;
            System.Console.WriteLine(ta.aa);
            System.Console.WriteLine(ta.bb);
            System.Console.WriteLine(tb.aa);
            System.Console.WriteLine(tb.bb);
        }

    }


    
public class AA
    
{
        
public int aa = 0;
        
        
public int bb = 0;
    }


简单吧!!

posted @ 2008-04-22 11:35  Adam.Zhao  阅读(699)  评论(1编辑  收藏  举报