循环遍历一个对象并找到not null属性

New*_*low 7 .net c# reflection

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

 if (o1.property1 != null) o1.property1 = o2.property1 
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

Jon*_*eet 12

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

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)