开发者

Using reflection copy object properties to another object

开发者 https://www.devze.com 2023-02-18 13:00 出处:网络
HI开发者_如何学运维, I have code below but getting error \"object does not match target type\"

HI开发者_如何学运维,

I have code below but getting error "object does not match target type" on the prop.SetValue statement. But the types are both 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. I think you should get all properties of TBR.Domain.Project and find one that has corresponding name.


I think you should call GetValue on the PropertyInfo corresponding to the Project type. PropertyInfo instances are tied to a specific type.

Basically, for each property info of the UniqueProjectType type, you have to look for a PropertyInfo on the Project type with the same name. Then you call GetValue and SetValue for the two objects using their corresponding PropertyInfo.

0

精彩评论

暂无评论...
验证码 换一张
取 消