c# 克隆方法中的对象

代码一(实现):

using System;

using System.Reflection;
namespace conTest
{
    class person
    {
        public string name { get; set; }
        public int age { get; set; }
        public double height { get; set; }

        public person(string name, int age, double height) 
        {
            this.name=name;
            this.age=age;
            this.height=height;
        }
        /// <summary>
        /// 克隆一个对象
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public object CloneObject(object o)
        {
            Type t = o.GetType();
            PropertyInfo[] properties = t.GetProperties();
            Object p = t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, o, null);
            foreach (PropertyInfo pi in properties)
            {
                if (pi.CanWrite)
                {
                    object value = pi.GetValue(o, null);
                    pi.SetValue(p, value, null);
                }
            }
            return p;
        }
    }
}

 

代码二(调用):

using System;
namespace conTest
{
    class Program
    {
        static void Main(string[] args)
        {
            person p1 = new person("bob", 22, 165);
            person p2 = new person("lingda", 21, 160);
            person p3 = (person)p1.CloneObject(p1);
            p1.name = p2.name;
            p1.age = p2.age;
            p1.height = p2.height;
            p2.name = p3.name;
            p2.age = p3.age;
            p2.height = p3.height;
            Console.WriteLine(p1.name + p1.age + p1.height);
            Console.WriteLine(p2.name + p2.age + p2.height);
            Console.ReadLine();
        }
    }
}

 

来源: (1条消息)【c# 克隆方法中的对象】 - CSDN

weinxin
我的微信
一个码农、工程狮、集能量和智慧于一身的、DIY高手、小伙伴er很多的、80后奶爸。
Igor
  • 版权声明: 发表于 2020-01-0817:15:12
  • 转载注明:http://blog.tsingmac.com/prolions/codelanguage/mscs/2414/
.NET 升级助手概述 C/C++/C#

.NET 升级助手概述

你可能有些应用当前正在 .NET Framework 上运行,而你想将它们移植到 .NET 6。 .NET 升级助手工具可帮助完成此过程。 本文提供以下内容: .NET 升级助手概述。 你可能有些应用...
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: