gpt4 book ai didi

c# - 使用反射和扩展方法在对象之间复制属性

转载 作者:太空宇宙 更新时间:2023-11-03 14:14:14 25 4
gpt4 key购买 nike

这是我的代码,我将一个对象(实体)的“副本”创建到自定义对象中。
它只复制源和目标中具有相同名称的属性。

我的问题是当一个实体有一个到另一个实体的导航时,对于这种情况,我添加了一个自定义属性,我在自定义类的属性上方添加了该属性。

例如自定义类如下所示:

public class CourseModel:BaseDataItemModel
{
public int CourseNumber { get; set; }

public string Name { get; set; }

LecturerModel lecturer;

[PropertySubEntity]
public LecturerModel Lecturer
{
get { return lecturer; }
set { lecturer = value; }
}

public CourseModel()
{
lecturer = new LecturerModel();
}

}

问题出在 targetProp.CopyPropertiesFrom(sourceProp); 行,当我尝试再次调用扩展方法(复制嵌套对象)时,因为类型是在运行时确定的,扩展方法无法在编译时解决。

也许我遗漏了什么......

public static void CopyPropertiesFrom(this BaseDataItemModel targetObject, object source)
{
PropertyInfo[] allProporties = source.GetType().GetProperties();
PropertyInfo targetProperty;

foreach (PropertyInfo fromProp in allProporties)
{
targetProperty = targetObject.GetType().GetProperty(fromProp.Name);
if (targetProperty == null) continue;
if (!targetProperty.CanWrite) continue;

//check if property in target class marked with SkipProperty Attribute
if (targetProperty.GetCustomAttributes(typeof(SkipPropertyAttribute), true).Length != 0) continue;

if (targetProperty.GetCustomAttributes(typeof(PropertySubEntity), true).Length != 0)
{
//Type pType = targetProperty.PropertyType;
var targetProp = targetProperty.GetValue(targetObject, null);
var sourceProp = fromProp.GetValue(source, null);

targetProp.CopyPropertiesFrom(sourceProp); // <== PROBLEM HERE
//targetProperty.SetValue(targetObject, sourceEntity, null);

}
else
targetProperty.SetValue(targetObject, fromProp.GetValue(source, null), null);
}
}

最佳答案

你必须先施法。

((BaseDataItemModel)targetProp).CopyPropertiesFrom(sourceProp); 

关于c# - 使用反射和扩展方法在对象之间复制属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6961248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com