您的位置:首页 > 编程语言 > C#

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

2016-02-03 10:57 477 查看


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

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: