C# - 将属性值从一个实例复制到另一个不同的类

标签 c# reflection properties mapping

我有两个 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'sDave'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/

相关文章:

C# 内部 getter,具有内部类参数的 protected setter

c# - 如何从 GridView 获取值并将其传递给 GridView 中 DropDownList 调用的方法?

c# - 如何为一个列表中的不同类型的值设计工厂模式?

C#、反射和原始类型

java - 从 getDeclaredMethods 中查找具有实际类型的泛型方法

java - 为 kafka 消费者使用多个反序列化器

c# - 使用私有(private)还是使用属性? C#

c# - C#获取单个文件最近创建时间的路径

Java:从 JAR 文件中的类文件中获取方法 stub 的简单方法?反射?

c# - 在 C# 中访问内部绑定(bind)类方法的更好方法是什么?