简体   繁体   中英

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

Advantages:

  • it stops your CPU from getting too cold by making sure it uses the maximum CPU cycles to do something simple
  • 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
  • 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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