你将如何改进这个浅复制类?

发布于 2024-07-12 11:11:45 字数 760 浏览 8 评论 0原文

我编写了一个带有单个静态方法的类,该方法将属性值从一个对象复制到另一个对象。 它不关心每个对象是什么类型,只关心它们具有相同的属性。 它满足了我的需要,因此我不会进一步对其进行设计,但是您会做出哪些改进?

这是代码:

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

我使用它的方式如下:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一笔一画续写前缘 2024-07-19 11:11:46

您的 DTO 可以序列化吗? 我希望如此,在这种情况下:

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

但请注意,我并不真正同意这种一般方法。 我更喜欢在每个 DTO 实施的 DTO 上进行复制的强有力的合同。

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.

执笏见 2024-07-19 11:11:46
  • 更改类型参数名称以符合命名约定,例如 TFrom 和 TTo,或 TSource 和 TDest(或 TDestination)。

    更改类型参数名称以符合命名

  • 在泛型类型中完成大部分工作,而不仅仅是在泛型方法中。 这允许您缓存属性,并允许类型推断。 类型推断对于“TFrom”参数很重要,因为它将允许使用匿名类型。

  • 您可以通过动态生成代码来进行属性复制并将其保存在对“from”类型有效的委托中,从而使其速度快得令人眼花缭乱。 或者可能为每个从/到对生成它,这意味着实际复制根本不需要使用反射! (准备代码将是每对类型的一次性命中,但希望您不会有太多对。)

  • Change your type parameter names to comply with naming conventions, e.g. TFrom and TTo, or TSource and TDest (or TDestination).

  • Do most of your work in a generic type instead of in just a generic method. That allows you to cache the properties, as well as allowing type inference. Type inference is important on the "TFrom" parameter, as it will allow anonymous types to be used.

  • You could potentially make it blindingly fast by dynamically generating code to do the property copying and keeping it in a delegate which is valid for the "from" type. Or potentially generate it for every from/to pair, which would mean the actual copying wouldn't need to use reflection at all! (Preparing the code would be a one-time hit per pair of types, but hopefully you wouldn't have too many pairs.)

断爱 2024-07-19 11:11:46

创建 To 的新实例并在返回之前调用 Copy() 方法的新方法可能会很有用。

像这样:

public static To Create<From, To>(From from)
    where To : class, new()
    where From : class
{
    var to = new To();
    Copy(from, to);
    return to;
}

A new method that created a new instance of To and called the Copy() method before returning might be useful.

Like this:

public static To Create<From, To>(From from)
    where To : class, new()
    where From : class
{
    var to = new To();
    Copy(from, to);
    return to;
}
拔了角的鹿 2024-07-19 11:11:46

确定如果传递的对象类型共享某些属性但不是全部属性,您要做什么。 在尝试设置属性值之前,请检查 From 对象和 To 对象中的属性是否存在。 当您来到一个不存在的房产时,做“正确的事”。 如果所有公共属性都需要相同,那么您需要检查是否已在 To 对象上设置所有属性,并处理未正确设置的情况。

我还建议您可能想要使用属性来装饰需要复制的属性并忽略其他属性。 这将使您能够更轻松地在两个不同的对象之间来回切换,并继续维护一些派生的公共属性,而不是存储在业务对象上的公共属性。

Decide what you want to do if passed objects of types that share some properties but not all. Check for the existence of the property in the From object in the To object before trying to set it's value. Do the "right thing" when you come to a property that doesn't exist. If all of the public properties need to be identical, then you will need to check if you've set all of them on the To object and handle the case where you haven't appropriately.

I'd also suggest that you may want to use attributes to decorate the properties that need to be copied and ignore others. This would allow you to go back and forth between the two different objects more easily and continue to maintain some public properties that are derived rather than stored on your business object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文