假设我有两个类:
public class Student
{
public int Id {get; set;}
public string Name {get; set;}
public IList<Course> Courses{ get; set;}
}
public class StudentDTO
{
public int Id {get; set;}
public string Name {get; set;}
public IList<CourseDTO> Courses{ get; set;}
}
我想从 Student 类复制值到 StudentDTO 类:
var student = new Student();
StudentDTO studentDTO = student;
我如何通过反射或其他解决方案来做到这一点?
最佳答案
列表让它变得棘手……我之前的回复(如下)仅适用于同类属性(不适用于列表)。我怀疑您可能只需要编写和维护代码:
Student foo = new Student {
Id = 1,
Name = "a",
Courses = {
new Course { Key = 2},
new Course { Key = 3},
}
};
StudentDTO dto = new StudentDTO {
Id = foo.Id,
Name = foo.Name,
};
foreach (var course in foo.Courses) {
dto.Courses.Add(new CourseDTO {
Key = course.Key
});
}
编辑;仅适用于浅副本 - 不适用于列表
反射是一种选择,但速度较慢。在 3.5 中,您可以使用 Expression
将其构建到一段已编译的代码中。 Jon Skeet 在 MiscUtil 中有一个预卷样本- 只需用作:
Student source = ...
StudentDTO item = PropertyCopy<StudentDTO>.CopyFrom(student);
因为它使用编译的Expression
,所以它的性能将大大优于反射。
如果你没有3.5,那就用反射或者ComponentModel。如果你使用 ComponentModel,你至少可以使用 HyperDescriptor
使其几乎与 Expression
Student source = ...
StudentDTO item = new StudentDTO();
PropertyDescriptorCollection
sourceProps = TypeDescriptor.GetProperties(student),
destProps = TypeDescriptor.GetProperties(item),
foreach(PropertyDescriptor prop in sourceProps) {
PropertyDescriptor destProp = destProps[prop.Name];
if(destProp != null) destProp.SetValue(item, prop.GetValue(student));
}
关于c# - 如何在 C# 中将值从 X 类复制到具有相同属性名称的 Y 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/531505/