一、兩個實體數據轉換
/// <summary>
/// 為屬性賦值
/// </summary>
/// <typeparam name="T">源單類</typeparam>
/// <typeparam name="S">需要轉換的實體類</typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static S EntityConvert<T, S>(T source)
{
S target = Activator.CreateInstance<S>();
var sType = source.GetType();
var dType = typeof(S);
foreach (PropertyInfo now in sType.GetProperties())
{
var name = dType.GetProperty(now.Name);
if (name == null)
continue;
dType.GetProperty(now.Name).SetValue(target, now.GetValue(source));
}
return target;
}
/// <summary>
/// 為屬性賦值
/// </summary>
/// <typeparam name="T">源單類</typeparam>
/// <typeparam name="S">需要轉換的實體類</typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static S EntityConvert<T, S>(T source)
{
S target = Activator.CreateInstance<S>();
var sType = source.GetType();
var dType = typeof(S);
foreach (PropertyInfo now in sType.GetProperties())
{
var name = dType.GetProperty(now.Name);
if (name == null)
continue;
dType.GetProperty(now.Name).SetValue(target, now.GetValue(source));
}
return target;
}
二、兩個集合之間的轉換
public static List<S> EntityConvert<T, S>(List<T> sourceList)
{
List<S> list = new List<S>();
IEnumerator<T> enumerator = sourceList.GetEnumerator();
while (enumerator.MoveNext())
{
list.Add(EntityConvert<T, S>(enumerator.Current));
}
return list;
}
三、獲取屬性的名稱、屬性類型、屬性值
public class User
{
public int Id { get; set; }
public string name { get; set; }
public decimal money { get; set; }
public string sex { get; set; }
public string Email { get; set; }
public DateTime birth { get; set; }
public int State { get; set; }
}
public void Test(){
var user = new User
{
birth = DateTime.Now,
Email = "123@qq.com",
Id = 1,
money = 123,
name = "張三",
sex = "男",
State = 1
};
var type = user.GetType().GetProperties();
foreach (var item in type)
{
Console.WriteLine($"屬性名稱:{item.Name},屬性值:{ item.GetValue(user)},屬性類型:{item.PropertyType.Name}");
}
}
public class User
{
public int Id { get; set; }
public string name { get; set; }
public decimal money { get; set; }
public string sex { get; set; }
public string Email { get; set; }
public DateTime birth { get; set; }
public int State { get; set; }
}
public void Test(){
var user = new User
{
birth = DateTime.Now,
Email = "123@qq.com",
Id = 1,
money = 123,
name = "張三",
sex = "男",
State = 1
};
var type = user.GetType().GetProperties();
foreach (var item in type)
{
Console.WriteLine($"屬性名稱:{item.Name},屬性值:{ item.GetValue(user)},屬性類型:{item.PropertyType.Name}");
}
}
