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

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

问题描述

假如我有两类:

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,你至少可以使用<一个href="http://www.$c$cproject.com/KB/cs/HyperPropertyDescriptor.aspx"><$c$c>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));
}

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

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