通过对象循环,找到不为空性(loop through an object and find the

2019-08-02 07:22发布

我也有同样的对象,O1,O2和2个实例。 如果我做这样的事情

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

在对象的所有属性。 什么是最有效的方式来遍历一个对象的所有属性做到这一点? 我看到使用的PropertyInfo检查属性nulll人,但好像他们只能通过收集的PropertyInfo得到却又无法链接性的操作。

谢谢。

Answer 1:

你可以用反射做到这一点:

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


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


Answer 3:

如果你要使用很多次,你可以使用编译表达式为更好的性能:

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


文章来源: loop through an object and find the not null properties