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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章