将属性值从一个实例复制到另一个实例,不同的类
  我有两个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和Dave的答案,我选择了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。
有这样的框架,我知道的是Automapper:
http://automapper.codeplex.com/
http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/01/22/automapper-the-object-object-mapper.aspx
用这个替换你的错误行:
PropertyInfo targetProperty = defectViewModel.GetType().GetProperty(defectProperty.Name);
targetProperty.SetValue(viewModel, defectValue, null);
  您发布的代码尝试在DefectViewModel对象上设置Defect tied属性。 
上一篇: copying property values from one instance to another, different classes
下一篇: size format provider
