简体   繁体   English

将反射复制对象属性用于另一个对象

[英]Using reflection copy object properties to another object

HI, HI,

I have code below but getting error "object does not match target type" on the prop.SetValue statement. 我有下面的代码,但在prop.SetValue语句中得到错误“对象与目标类型不匹配”。 But the types are both Int32. 但类型都是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;
    }

I think here's the catch: 我认为这是一个问题:

prop.GetValue(project, null);

prop is specific to UniqueProjectType while project is TBR.Domain.Project type. prop特定于UniqueProjectTypeprojectTBR.Domain.Project类型。 I think you should get all properties of TBR.Domain.Project and find one that has corresponding name. 我想你应该获得TBR.Domain.Project所有属性,并找到一个具有相应名称的属性。

I think you should call GetValue on the PropertyInfo corresponding to the Project type. 我认为你应该在与Project类型对应的PropertyInfo上调用GetValue。 PropertyInfo instances are tied to a specific type. PropertyInfo实例绑定到特定类型。

Basically, for each property info of the UniqueProjectType type, you have to look for a PropertyInfo on the Project type with the same name. 基本上,对于UniqueProjectType类型的每个属性信息,您必须在Project类型上查找具有相同名称的PropertyInfo。 Then you call GetValue and SetValue for the two objects using their corresponding PropertyInfo. 然后使用相应的PropertyInfo为两个对象调用GetValue和SetValue。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM