遍历对象并查找非空属性。

7

我有两个相同的对象实例,o1和o2。如果我正在进行以下操作:

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

对于对象中的所有属性,如何最有效地循环遍历所有属性并执行操作?我看到有人使用PropertyInfo来检查属性的空值,但似乎他们只能通过PropertyInfo集合访问属性而不能链接属性的操作。

谢谢。

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);
        }
    }
}

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);
    }
}

我会制作一个通用版本,以确保两个对象具有相同的类型 :) - khellang
@khellang 很棒的想法 :), 我改了我的例子。 - Jan-Peter Vos
@khellang:但这并不能保证。例如,以下代码可以编译通过:CopyTo<object>(new Button(), new Object())。我最初将我的代码设计成通用的,但后来发现它并没有真正起到帮助作用,于是将其删除了。 - Jon Skeet

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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接