using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
public class Person {
public Person(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; }
}
public class User {
public int Id { get; set; }
public string Name { get; set; }
public string Group { get; set; }
}
public class DemoClass{
public static User ConvertObject(User user,Person person)
{
PropertyInfo[] userPro = user.GetType().GetProperties();
PropertyInfo[] personPro = person.GetType().GetProperties();
if (userPro.Length>0&&personPro.Length>0)
{
for (int i = 0; i < userPro.Length; i++)
{
for (int j = 0; j < personPro.Length; j++)
{
if (userPro[i].Name == personPro[j].Name && userPro[i].PropertyType == personPro[j].PropertyType)
{
Object value=personPro[j].GetValue(person, null);
userPro[i].SetValue(user,value , null);
}
}
}
}
return user;
}
public static T1 ConvertObject2<T1,T2>(T1 user,T2 person)
{
PropertyInfo[] userPro = user.GetType().GetProperties();
PropertyInfo[] personPro = person.GetType().GetProperties();
if (userPro.Length>0&&personPro.Length>0)
{
for (int i = 0; i < userPro.Length; i++)
{
for (int j = 0; j < personPro.Length; j++)
{
if (userPro[i].Name == personPro[j].Name && userPro[i].PropertyType == personPro[j].PropertyType)
{
Object value=personPro[j].GetValue(person, null);
userPro[i].SetValue(user,value , null);
}
}
}
}
return user;
}
public static T ConvertDic<T>(Dictionary<string, object> dic)
{
T model = Activator.CreateInstance<T>();
PropertyInfo[] modelPro = model.GetType().GetProperties();
if (modelPro.Length > 0 && dic.Count() > 0)
{
for (int i = 0; i < modelPro.Length; i++)
{
if (dic.ContainsKey(modelPro[i].Name))
{
modelPro[i].SetValue(model, dic[modelPro[i].Name], null);
}
}
}
return model;
}
static void Main(string[] args)
{
Person person = new Person(1,"FlyElephant","北京");
User user = new User();
user.Id = 20;
user = ConvertObject(user, person);
Console.WriteLine("Id:" + user.Id + "Name:" + user.Name + "角色:" + user.Group);
person = new Person(2,"ffh","合肥");
user = ConvertObject2<User,Person>(user, person);
Console.WriteLine("Id:" + user.Id + "Name:" + user.Name + "角色:" + user.Group);
Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("Id",10086);
dic.Add("Name", "ffh");
dic.Add("Group", "程序员");
user = ConvertDic<User>(dic);
Console.WriteLine("Id:" + user.Id + "Name:" + user.Name + "角色:" + user.Group);
System.Console.Read();
}
}