遍历对象并找到非null属性 [英] loop through an object and find the not null properties

查看:53
本文介绍了遍历对象并找到非null属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 2 instances of the same objects, o1, and o2. If I am doing things like

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

用于对象中的所有属性.遍历对象中的所有属性并做到这一点的最有效方法是什么?我看到人们使用PropertyInfo检查属性的空值,但似乎他们只能通过PropertyInfo集合,而不能链接属性的操作.

for all the properties in the object. What would be the most efficient way to loop through all properties in an Object and do that? I saw people using PropertyInfo to check nulll of the properties but it seems like they could only get through the PropertyInfo collection but not link the operation of the properties.

谢谢.

推荐答案

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

You can do this with reflection:

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

这篇关于遍历对象并找到非null属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆