C# 不同类型对象同名属性赋值

时间:2022-03-09 04:42:35
/// <summary>
/// 不同类型对象同名属性赋值
/// </summary>
/// <typeparam name="S">源类型</typeparam>
/// <typeparam name="T">目标类型</typeparam>
/// <param name="s">源对象</param>
/// <param name="t">目标对象</param>
public static void AutoMapping<S, T>(S s, T t)
{
PropertyInfo[] pps = GetPropertyInfos(s.GetType());
Type target = t.GetType(); foreach (var pp in pps)
{
try
{
PropertyInfo targetPP = target.GetProperty(pp.Name);
object value = pp.GetValue(s, null); if (targetPP != null && value != null)
{
targetPP.SetValue(t, value, null);
}
}
catch (Exception ex)
{
throw ex;
}
}
}