.net两个对象相同属性赋值
电脑版发表于:2019/9/12 11:49
两个对象相同属性赋值,可以减少一个一个属性点出来赋值,用一点反射即可搞定
public class ModelTools
{
/// <summary>
/// 模型赋值
/// </summary>
/// <param name="target">目标</param>
/// <param name="source">数据源</param>
public static void CopyModel(object target, object source)
{
Type targetType = target.GetType();
Type sourceType = source.GetType();
foreach (var mi in sourceType.GetProperties())
{
var des = targetType.GetProperty(mi.Name);
if (des != null)
{
des.SetValue(target, mi.GetValue(source));
}
}
}
}用法:

如果不是每一个一样的都需要去拷贝,我们还可以设置忽略,直接传递需要忽略的属性名称即可,没有必要去搞一个什么特性配置反而麻烦了
泛型方法的写法:
/// <summary>
/// 模型赋值
/// </summary>
/// <param name="target">目标</param>
/// <param name="source">数据源</param>
public static void CopyModel<T, M>(T target, M source)
{
Type targetType = target.GetType();
Type sourceType = source.GetType();
foreach (var mi in sourceType.GetProperties())
{
var des = targetType.GetProperty(mi.Name);
if (des != null)
{
des.SetValue(target, mi.GetValue(source));
}
}
}