我有两个 C# 类,它们具有许多相同的属性(按名称和类型)。我希望能够从 Defect
的实例中复制所有非空值进入 DefectViewModel
的实例.我希望通过反射来做到这一点,使用 GetType().GetProperties()
.我尝试了以下方法:
var defect = new Defect();
var defectViewModel = new DefectViewModel();
PropertyInfo[] defectProperties = defect.GetType().GetProperties();
IEnumerable<string> viewModelPropertyNames =
defectViewModel.GetType().GetProperties().Select(property => property.Name);
IEnumerable<PropertyInfo> propertiesToCopy =
defectProperties.Where(defectProperty =>
viewModelPropertyNames.Contains(defectProperty.Name)
);
foreach (PropertyInfo defectProperty in propertiesToCopy)
{
var defectValue = defectProperty.GetValue(defect, null) as string;
if (null == defectValue)
{
continue;
}
// "System.Reflection.TargetException: Object does not match target type":
defectProperty.SetValue(viewModel, defectValue, null);
}
执行此操作的最佳方法是什么?我应该维护 Defect
的单独列表吗?属性和 DefectViewModel
属性,以便我可以做 viewModelProperty.SetValue(viewModel, defectValue, null)
?
编辑:感谢Jordão's和 Dave's答案,我选择了AutoMapper。 DefectViewModel
在 WPF 应用程序中,所以我添加了以下 App
构造函数:
public App()
{
Mapper.CreateMap<Defect, DefectViewModel>()
.ForMember("PropertyOnlyInViewModel", options => options.Ignore())
.ForMember("AnotherPropertyOnlyInViewModel", options => options.Ignore())
.ForAllMembers(memberConfigExpr =>
memberConfigExpr.Condition(resContext =>
resContext.SourceType.Equals(typeof(string)) &&
!resContext.IsSourceValueNull
)
);
}
然后,而不是所有PropertyInfo
业务,我只有以下行:
var defect = new Defect();
var defectViewModel = new DefectViewModel();
Mapper.Map<Defect, DefectViewModel>(defect, defectViewModel);
最佳答案
看看AutoMapper .
关于C# - 将属性值从一个实例复制到另一个不同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3610891/