几年前有写过一篇文章,找不到了,这里贴下实验代码:
public class ModelBinding
{
/// <summary>
/// 模型赋值
/// </summary>
/// <param name="target">目标</param>
/// <param name="source">数据源</param>
public static void CopyModel(object target, object source)
{
Type type1 = target.GetType();
Type type2 = source.GetType();
foreach (var mi in type2.GetProperties())
{
var des = type1.GetProperty(mi.Name);
if (des != null)
{
try
{
des.SetValue(target, mi.GetValue(source, null), null);
}
catch
{ }
}
}
}
}
做的好一点,这里应该把GetProperties()的结果缓存起来,不用个每次都反射