简体   繁体   English

c# - 继承 + 反射 - 如何不克隆对象

[英]c# - inheritence + reflection - how not to clone an object

I found the following code snippet which puzzled me.我发现以下代码片段让我感到困惑。

public class Bclass : Aclass
{
    public const BindingFlags Flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;

    public Bclass(IAclass a) : base(string.Empty)
    {
        var destFields = this.GetType().BaseType.GetFields( Flags );

        a.GetType().GetFields( Flags ).Where(x => destFields.Contains(x)).ToList().ForEach(property =>
        {
            destFields.First(x => x == property).SetValue(this, property.GetValue(a));
        });

        var destProperties = this.GetType().BaseType.GetProperties( Flags );

        a.GetType().GetProperties( Flags ).Where(x => destProperties.Contains(x)).ToList().ForEach(property =>
        {
            destProperties.First(x => x == property).SetValue(this, property.GetValue(a, null));
        });
    }
    // some more methods... 
}

My main Q is.... why would anyone think of doing that... What benefit(s) can come out of this code.我的主要问题是......为什么会有人想到这样做......这段代码可以带来什么好处。

What it does: memberwise clone from a into the current newly created instance它的作用:从a成员方式克隆到当前新创建的实例中

Advantages:好处:

  • it stops your CPU from getting too cold by making sure it uses the maximum CPU cycles to do something simple它通过确保它使用最大 CPU 周期来做一些简单的事情来防止你的 CPU 变得太冷
  • it keeps the GC on its toes by doing a great amount of allocation in a simple object constructor without any of those crazy ideas like strategy caches它通过在一个简单的对象构造函数中进行大量分配来保持 GC 处于正常状态,而没有任何像策略缓存这样的疯狂想法
  • it kinda reduces maintenance of having to write manual "copy the members" code, but: there are tools that do that very well and very efficiently that should be employed;有点减少了必须编写手动“复制成员”代码的维护,但是:有一些工具可以非常好且非常有效地做到这一点,应该使用; or if that isn't an option, there are still *many ways of improving this code without making it insanely complex或者如果这不是一个选项,仍然有*多种方法可以改进此代码而不会使它变得异常复杂

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM