C# PropertyInfo 将一个对象赋值到另一个相同名称的对象

来源:互联网 发布:协同过滤推荐算法实例 编辑:程序博客网 时间:2024/06/16 00:01


using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Reflection;namespace ConsoleApplication8{    class Program    {        static void Main(string[] args)        {            T1 t1 = new T1(1,"t1_Name","t1_Address");            T2 t2 = new T2();            t2.ID = 3;            t2 = ConvertT(t1, t2);            Console.WriteLine("ID:{0},Name:{1},Group:{2}", t2.ID, t2.Name, t2.Group);        }        static T2 ConvertT(T1 t1,T2 t2)        {            PropertyInfo[] p1 = t1.GetType().GetProperties();            PropertyInfo[] p2 = t2.GetType().GetProperties();            foreach (var item in p1)            {                foreach (var itme2 in p2)                {                    if (item.Name == itme2.Name && item.PropertyType == itme2.PropertyType)                    {                        Object obj = item.GetValue(t1,null);                        itme2.SetValue(t2, obj,null);                    }                }            }            return t2;        }    }    class T1    {        public T1(int id, string name,string address)        {            this.ID = id;            this.Name = name;            this.Address = address;        }        public int ID { get; set; }        public string Name { get; set; }        public string Address { get; set; }    }    class T2    {        public int ID { get; set; }        public string Name { get; set; }        public string Group { get; set; }    }}


0 0