首页 > 其他 > 详细

C# 克隆一个对象(实例)

时间:2014-04-07 14:00:49      阅读:562      评论:0      收藏:0      [点我收藏+]

代码一:

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

C# 克隆一个对象(实例),布布扣,bubuko.com

C# 克隆一个对象(实例)

原文:http://blog.csdn.net/coolfeiweb/article/details/23096553

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!