代码一(实现):
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(); } } }
文章末尾固定信息

我的微信
我的微信
一个码农、工程狮、集能量和智慧于一身的、DIY高手、小伙伴er很多的、80后奶爸。
评论