The dawn of modern programmers

現代プログラマーの朝焼け

リフレクションでオブジェクトのDeep Copy

制約はあるけど簡単なValueObjectであればこれでDeepcopyできたり。
使いすぎるとパフォーマンスに影響出ますね。

using System;
using System.Reflection;

namespace HogeHoge
{
    public class CloneGenerator
    {

        public static T Clone<T>(T target) where T: new()
        {
            T clone = new T();
            FieldInfo[] fields = target.GetType().GetFields(
                BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            foreach (FieldInfo field in fields)
            {
                field.SetValue(clone, field.GetValue(target));
            }
            
            return clone;
        }

    }
}