c# - 如何在 C# 中将值从 X 类复制到具有相同属性名称的 Y 类?

标签 c# .net reflection

假设我有两个类:

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/

相关文章:

c# - 通过反射创建委托(delegate)

c# - 如何获取转换后的 bool 值以在 asp.net gridview 的可编辑下拉列表中显示为选定值?

c# - Asp.Net MVC - 查看 -> 创建 2 个对象

c# - 转换方法以使用任何枚举

c# - LastOrDefault() 和 Last() 方法是否迭代列表的每个元素?

c# - 如何使用反射获取 C# 静态类属性的名称?

java - 动态调用实现方法

c# - 生成动态旋转

.net - Monotouch命令行构建不起作用

.net - 如何在 .Net 中使用 Confluence.Kafka 从特定 TopicPartitionOffset 进行消费