c#两个对象,同属性赋值

来源:互联网 发布:网络在线教育迎着 编辑:程序博客网 时间:2024/06/08 03:56

几年前有写过一篇文章,找不到了,这里贴下实验代码:

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()的结果缓存起来,不用个每次都反射