一、两个实体数据转换
/// <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 = ,
money = ,
name = "张三",
sex = "男",
State =
};
var type = user.GetType().GetProperties();
foreach (var item in type)
{
Console.WriteLine($"属性名称:{item.Name},属性值:{ item.GetValue(user)},属性类型:{item.PropertyType.Name}");
}
}