fox-net’s blog

システム開発に間することをざっくばらんに

C#で異なるクラス間のプロパティ値コピー

Entityframeworkを使っていると、
ViewModelとDomainModel間で同名のプロパティをコピーしたい!
なんてことよくありますよね。

というわけで、作ってみました。


今回は拡張メソッドにしてみます。

public static class Extention
{
    public static void CopyProperty(this object toObject, object fromObject)
    {
        // コピー元、コピー先のプロパティ情報を取得
        PropertyInfo[] fromProperties = fromObject.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
        PropertyInfo[] toProperties = toObject.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (var fromProperty in fromProperties)
        {
            // 名前と型が同じプロパティを取得
            PropertyInfo target = Array.Find(toProperties, to => to.Name.Equals(fromProperty.Name)
                                             && to.PropertyType.Equals(fromProperty.PropertyType));

            // プロパティ値コピー
            if (target != null)
                target.SetValue(toObject, fromProperty.GetValue(fromObject));
        }

    }
}


使い方は以下の通り

コピー元クラス

    public class FromObject
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public bool? Nullable { get; set; }

        public string OnlyFrom { get; set; }

        public int SameName { get; set; }
    }

コピー先クラス

    public class ToObject
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public bool Nullable { get; set; }

        public string OnlyTo { get; set; }

        public string SameName { get; set; }
    }
    class MainClass
    {
        public static void Main(string[] args)
        {
            FromObject from = new FromObject()
            {
                Id = 1,
                Name = "hoge",
                Nullable = true,
                OnlyFrom = "foo",
                SameName = 10
            };

            ToObject to = new ToObject();

            to.CopyProperty(from);

            Console.WriteLine("ID:" + to.Id);

            Console.WriteLine("Name:" + to.Name);

            string sameName = to.SameName ?? "null";
            Console.WriteLine("SameName:" + sameName);

            Console.WriteLine("Nullable:" + to.Nullable);

            string onlyTo = to.OnlyTo ?? "null";
            Console.WriteLine("OnlyTo:" + onlyTo);
        }
    }


実行結果

ID:1
Name:hoge
SameName:null
Nullable:False
OnlyTo:null

名前と型が同じプロパティのみコピーされます。
null許容型は違う型とみなしコピーはしません。