C#深拷贝-创新互联

关于C#的深拷贝的实现方式:

定制开发可以根据自己的需求进行定制,网站设计、成都网站制作构思过程中功能建设理应排到主要部位公司网站设计、成都网站制作的运用实际效果公司网站制作网站建立与制做的实际意义

①反射

②反序列化

③表达式树

目前只讲解利用反射实现C#深拷贝的方法:

深拷贝工具类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace CopyDemo
{
    public sealed class CopyTools
    {
        public static T DeepCopy(T obj)
        {
            //如果是字符串或值类型则直接返回
            if (obj is string || obj.GetType().IsValueType) return obj;
            object retval = Activator.CreateInstance(obj.GetType());
            FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
            foreach (FieldInfo field in fields)
            {
                try { field.SetValue(retval, DeepCopy(field.GetValue(obj))); }
                catch { }
            }
            return (T)retval;
        }
    }
}

下面2个类用于测试:

宠物类->

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CopyDemo
{
    public sealed class Pet
    {
        public string Name { get; set; }
    }
}

人物类->

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CopyDemo
{
    public sealed class People
    {
        public string Name { set; get; }
        public Pet My_Pet { get; set; }
    }
}

测试代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CopyDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            People A = new People() {My_Pet = new Pet()};
            A.Name = "Aonaufly";
            A.My_Pet.Name = "小白";
            Console.WriteLine("=================================================");
            People _copyA = CopyTools.DeepCopy(A);
            _copyA.Name = "Kayer";
            _copyA.My_Pet.Name = "旺财";
            Console.WriteLine("源 name : {0} , petName : {1}" , A.Name,A.My_Pet.Name);
            Console.WriteLine("Copy name : {0} , petName : {1}", _copyA.Name, _copyA.My_Pet.Name);
            Console.ReadKey();
        }
    }
}

运行结果:

C# 深拷贝

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


分享题目:C#深拷贝-创新互联
文章转载:http://pwwzsj.com/article/djspdd.html