将一个对象的字段值全部复制到另一个同类型对象

public static void Copy<T>(T from, T to)
{
    if (ReferenceEquals(from, null))
        throw new ArgumentNullException("from");
    if (ReferenceEquals(to, null))
        throw new ArgumentNullException("to");

    Type type = from.GetType();
    PropertyInfo[] fields = type.GetProperties();
    foreach (PropertyInfo p in fields)
    {
        p.SetValue(to, p.GetValue(from));
    }
}

发表评论

邮箱地址不会被公开。 必填项已用*标注