如何从类X复制值Y级在C#中的相同属性名称?属性、名称

2023-09-02 10:24:44 作者:只一眼便沦陷

假如我有两类:

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;}
}

我想从学生类值复制到StudentDTO类:

I would like to copy value from Student class to StudentDTO class:

var student = new Student();
StudentDTO studentDTO = student;

我怎么能做到这一点通过反射或其他解决方案?

How can I do that by reflection or other solution?

推荐答案

该列表使其棘手...我刚才的答复(见下文)只适用于像对等的性质(而不是列表)。我怀疑你可能只需要编写和维护code:

The lists make it tricky... my earlier reply (below) only applies to like-for-like properties (not the lists). I suspect you might just have to write and maintain code:

    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
        });
    }

Edit(编辑)仅适用于浅副本 - 不列出

edit; only applies to shallow copies - not lists

反思是一种选择,但速度缓慢。在3.5,你可以建立到code与编译位前pression 这一点。乔恩斯基特有这个在pre-推出样品 MiscUtil - 就像使用:

Reflection is an option, but slow. In 3.5 you can build this into a compiled bit of code with Expression. Jon Skeet has a pre-rolled sample of this in MiscUtil - just use as:

Student source = ...
StudentDTO item = PropertyCopy<StudentDTO>.CopyFrom(student);

由于这种使用编译防爆pression 将大大超出执行反射。

Because this uses a compiled Expression it will vastly out-perform reflection.

如果你没有3.5,然后用反射或ComponentModel。如果你使用ComponentModel,你至少可以使用HyperDescriptor得到它的近的那么快,防爆pression

If you don't have 3.5, then use reflection or ComponentModel. If you use ComponentModel, you can at least use HyperDescriptor to get it nearly as quick as 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));
}