7

我有 2 个相同对象的实例,o1 和 o2。如果我正在做类似的事情

 if (o1.property1 != null) o1.property1 = o2.property1 

对象中的所有属性。循环遍历 Object 中的所有属性并执行此操作的最有效方法是什么?我看到人们使用 PropertyInfo 来检查属性的 nulll,但似乎他们只能通过 PropertyInfo 集合而不是链接属性的操作。

谢谢。

4

3 回答 3

14

您可以通过反射来做到这一点:

public void CopyNonNullProperties(object source, object target)
{
    // You could potentially relax this, e.g. making sure that the
    // target was a subtype of the source.
    if (source.GetType() != target.GetType())
    {
        throw new ArgumentException("Objects must be of the same type");
    }

    foreach (var prop in source.GetType()
                               .GetProperties(BindingFlags.Instance |
                                              BindingFlags.Public)
                               .Where(p => !p.GetIndexParameters().Any())
                               .Where(p => p.CanRead && p.CanWrite))
    {
        var value = prop.GetValue(source, null);
        if (value != null)
        {
            prop.SetValue(target, value, null);
        }
    }
}
于 2012-11-03T19:36:31.757 回答
2

如果您要多次使用它,您可以使用编译表达式以获得更好的性能:

public static class Mapper<T>
{
    static Mapper()
    {
        var from = Expression.Parameter(typeof(T), "from");
        var to = Expression.Parameter(typeof(T), "to");

        var setExpressions = typeof(T)
            .GetProperties()
            .Where(property => property.CanRead && property.CanWrite && !property.GetIndexParameters().Any())
            .Select(property =>
            {
                var getExpression = Expression.Call(from, property.GetGetMethod());
                var setExpression = Expression.Call(to, property.GetSetMethod(), getExpression);
                var equalExpression = Expression.Equal(Expression.Convert(getExpression, typeof(object)), Expression.Constant(null));

                return Expression.IfThen(Expression.Not(equalExpression), setExpression);
            });

        Map = Expression.Lambda<Action<T, T>>(Expression.Block(setExpressions), from, to).Compile();
    }

    public static Action<T, T> Map { get; private set; }
}

并像这样使用它:

Mapper<Entity>.Map(e1, e2);
于 2012-11-04T07:21:58.447 回答
2

从你的例子来看,我认为你正在寻找这样的东西:

static void CopyTo<T>(T from, T to)
{
    foreach (PropertyInfo property in typeof(T).GetProperties())
    {
        if (!property.CanRead || !property.CanWrite || (property.GetIndexParameters().Length > 0))
            continue;

        object value = property.GetValue(to, null);
        if (value != null)
            property.SetValue(to, property.GetValue(from, null), null);
    }
}
于 2012-11-03T19:35:24.067 回答