你将如何改善这种浅拷贝类? [英] How would you improve this shallow copying class?

查看:101
本文介绍了你将如何改善这种浅拷贝类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了一类具有一个静态方法从一个对象复制属性值到另一个。它并不关心的每个对象是什么类型,只是它们具有相同的属性。 ?它做什么,我需要,所以我没有进一步的工程,但你会作出什么样的改进



下面的代码:

 公共类ShallowCopy 
{
公共静态无效的复制和LT;从,至大于(从从,为了向)
其中要:类
从哪儿:类
{
型toType = to.GetType();
的foreach(在from.GetType VAR的PropertyInfo()的GetProperties(BindingFlags.GetProperty |。BindingFlags.Public | BindingFlags.Instance))
{
toType.GetProperty(propertyInfo.Name).SetValue(于propertyInfo.GetValue(自,空),NULL);
}
}
}



我用它作为如下:

  EmployeeDTO DTO = GetEmployeeDTO(); 
员工员工=新员工();
ShallowCopy.Copy(DTO,员工);


解决方案

是你的序列化的DTO?我希望如此,在这种情况下:

 的MemberInfo [] SM = FormatterServices.GetSerializableMembers(typeof运算(从)); 
对象[]数据= FormatterServices.GetObjectData(从,SM);
FormatterServices.PopulateObjectMembers(于SM,数据);



但请注意,我真的不使用此一般方法达成一致。我宁愿为你的DTO每个DTO实现复制的强大的合同。


I've written a class with a single static method that copies property values from one object to another. It doesn't care what type each object is, only that they have identical properties. It does what I need, so I'm not engineering it further, but what improvements would you make?

Here's the code:

public class ShallowCopy
{
    public static void Copy<From, To>(From from, To to)
        where To : class
        where From : class
    {
        Type toType = to.GetType();
        foreach (var propertyInfo in from.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
        {
            toType.GetProperty(propertyInfo.Name).SetValue(to, propertyInfo.GetValue(from, null), null);
        }
    }
}

I'm using it as follows:

EmployeeDTO dto = GetEmployeeDTO();
Employee employee = new Employee();
ShallowCopy.Copy(dto, employee);

解决方案

Are your DTOs serializable? I would expect so, in which case:

MemberInfo[] sm = FormatterServices.GetSerializableMembers(typeof(From));
object[] data = FormatterServices.GetObjectData(from, sm);
FormatterServices.PopulateObjectMembers(to, sm, data);

But note that I don't really agree with this general approach. I would prefer a strong contract for copying on your DTOs that each DTO implements.

这篇关于你将如何改善这种浅拷贝类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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