我有两个相同对象的实例:o1 和 o2。如果我正在做类似的事情
if (o1.property1 != null) o1.property1 = o2.property1
对于对象中的所有属性。循环遍历对象中的所有属性并执行此操作的最有效方法是什么?我看到人们使用PropertyInfo来检查属性是否为空,但似乎他们只能通过PropertyInfo集合而无法链接属性的操作。
Thanks.
您可以通过反射来做到这一点:
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);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)