c# - 如何在c#中使用相同的属性名称将值从X类复制到Y类? [英] How to copy value from class X to class Y with the same property name in c#?

查看:18
本文介绍了c# - 如何在c#中使用相同的属性名称将值从X类复制到Y类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个类:

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 类:

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?

推荐答案

列表使它变得棘手...我之前的回复(如下)仅适用于同类属性(不适用于列表).我怀疑您可能只需要编写和维护代码:

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; only applies to shallow copies - not lists

反射是一种选择,但速度很慢.在 3.5 中,您可以使用 Expression 将其构建为编译后的代码.Jon Skeet 在 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);

因为它使用一个编译过的Expression,它的性能将大大优于反射.

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

如果您没有 3.5,则使用反射或 ComponentModel.如果使用ComponentModel,至少可以使用HyperDescriptor几乎Expression

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

这篇关于c# - 如何在c#中使用相同的属性名称将值从X类复制到Y类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆