C# 使用反射将对象属性复制到另一个对象

C# 使用反射将对象属性复制到另一个对象,c#,reflection,C#,Reflection,嗨 我有下面的代码,但获取错误对象与目标类型不匹配 在prop.SetValue语句中。但是类型都是Int32 private UniqueProjectType CreateUniqueProjectType(TBR.Domain.Project project) { UniqueProjectType type = new UniqueProjectType(); foreach (PropertyInfo prop in type.GetT

我有下面的代码,但获取错误对象与目标类型不匹配 在prop.SetValue语句中。但是类型都是Int32

    private UniqueProjectType CreateUniqueProjectType(TBR.Domain.Project project)
    {
        UniqueProjectType type = new UniqueProjectType();

        foreach (PropertyInfo prop in type.GetType().GetProperties())
        {
            if (prop.Name == "ID")
            {}
            else if (prop.Name == "PayFrequency")
                type.PayFrequency = _tbrService.GetEmployee((int)project.EmployeeID).PayFrequency;
            else
                prop.SetValue(type, prop.GetValue(project, null), null);

        }

        return type;
    }

我想这里有个问题:

prop.GetValue(project, null);

道具特定于UniqueProjectType,而项目为TBR.Domain.project类型。我认为您应该获取TBR.Domain.Project的所有属性,并找到一个具有相应名称的属性。

我认为这里有一个要点:

prop.GetValue(project, null);

道具特定于UniqueProjectType,而项目为TBR.Domain.project类型。我认为您应该获取TBR.Domain.Project的所有属性,并找到一个具有相应名称的属性。

我认为您应该调用与项目类型对应的PropertyInfo上的GetValue。PropertyInfo实例绑定到特定类型


基本上,对于UniqueProjectType类型的每个属性信息,必须在项目类型上查找同名的PropertyInfo。然后使用两个对象对应的PropertyInfo为它们调用GetValue和SetValue。

我认为应该对项目类型对应的PropertyInfo调用GetValue。PropertyInfo实例绑定到特定类型


基本上,对于UniqueProjectType类型的每个属性信息,必须在项目类型上查找同名的PropertyInfo。然后,使用两个对象对应的属性Info为它们调用GetValue和SetValue。

查看SetValue和GetValue方法的声明及其类型会很有帮助,否则我们只能假设发生了什么。@Raphael B:它们是内置的.NET类型Maybe Raphael B。这意味着查看哪个字段会很有帮助这是崩溃-需要知道数据类型,等等。查看SetValue和GetValue方法的声明以及它们的类型会很有帮助,否则我们只能假设发生了什么。@Raphael B:它们是内置的.NET类型Maybe Raphael B。这意味着查看它在哪个字段上崩溃会很有帮助-需要知道数据类型,等等。