• 实现深拷贝的一种方法


    声明接口:
        

        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;
        }


    简单吧!!

  • 相关阅读:
    AutoMapper使用
    C#网络编程
    ASP.NET MVC (Razor)开发
    React的React Native
    WCF搭建
    异步编程
    Async和Await进行异步编程
    C#开发中使用配置文件
    NET转Java
    net 开源组件
  • 原文地址:https://www.cnblogs.com/adam/p/1165282.html
Copyright © 2020-2023  润新知