可能是一个愚蠢的问题,但我在网上找不到任何解释。
这段代码为什么不能工作? 这段代码应该将Contact
(源)的属性值复制到新实例化的ContactBO
(目标)对象中。
public ContactBO(Contact contact)
{
Object source = contact;
Object destination = this;
PropertyInfo[] destinationProps = destination.GetType().GetProperties(
BindingFlags.Public);
PropertyInfo[] sourceProps = source.GetType().GetProperties(
BindingFlags.Public);
foreach (PropertyInfo currentProperty in sourceProps)
{
var propertyToSet = destinationProps.First(
p => p.Name == currentProperty.Name);
if (propertyToSet == null)
continue;
try
{
propertyToSet.SetValue(
destination,
currentProperty.GetValue(source, null),
null);
}
catch (Exception ex)
{
continue;
}
}
}
两个类具有相同的属性名称(BO类有一些其他属性,但在初始化时不重要)。两个类仅具有公共属性。 当我运行上面的示例时,destinationProps
和sourceProps
长度为零。
但是,当我使用BindingFlags.Instance
扩展GetProperties
方法时,它突然返回所有内容。希望有人能够对此事情进行解释,因为我很迷茫。
propertyToSet
与null
进行比较,则不应使用First
,因为如果找不到不匹配谓词的项,它会抛出异常。请改用FirstOrDefault
。 - ba__friend