クラスとクラス間の同じプロパティとフィールドのコピー

2775 ワード

主に異なるクラス間のメンバーの相互付与に対処するためである.コード量を節約します.
namespace ConsoleApplication3

{

    public interface interTest

    {



    }

    public class Test : interTest

    {

        public string Name;

        public int Id;

        public int TestId;

        public int Property { get; set; }



    }

    public class TestClone

    {

        public string Name;

        public int Id;

        public int CloneId;

        public int Property { get; set; }

    }

    public static class Logic

    {

        public static MemberTypes AllowType = MemberTypes.Field | MemberTypes.Property;



        public static void CloneField<T, T1>(this T instance, T1 copyTo) where T : class ,interTest, new()

        {

            var instanceType = instance.GetType();

            var copyType = copyTo.GetType();





            var copyField = copyType.GetFields();

            instanceType.GetFields().All(field =>

            {

                var temp = copyField.FirstOrDefault(o => o.Name.Equals(field.Name, StringComparison.CurrentCulture) && o.FieldType == field.FieldType);

                if (temp == null) return true;



                temp.SetValue(copyTo, field.GetValue(instance));

                return true;

            });







        }

        public static void CloneProperty<T, T1>(this T instance, T1 copyTo) where T : class ,interTest, new()

        {

            var instanceType = instance.GetType();

            var copyType = copyTo.GetType();



            var copyProperties = copyType.GetProperties();

            instanceType.GetProperties().All(property =>

            {

                var temp = copyProperties.FirstOrDefault(o => o.Name.Equals(property.Name, StringComparison.CurrentCulture) && o.PropertyType == property.PropertyType);

                if (temp == null) return true;



                temp.SetValue(copyTo, property.GetValue(instance, null), null);

                return true;

            });





        }

    }

}


 
よびだし
class Program

    {

        static void Main(string[] args)

        {

            Test t = new Test();

            t.Id = 1;

            t.Name = "shikyoh";

            t.TestId = 12;

            t.Property = 600;

            TestClone tc = new TestClone();

            t.CloneField(tc);

            t.CloneProperty(tc);



           

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

            Console.WriteLine("tc.Id:" + tc.Id);

            Console.WriteLine("tc.Property:" + tc.Property);

            Console.WriteLine("tc.CloneId:" + tc.CloneId);

        }

    }


 
注意クラスの名前は同じで、タイプは同じでなければなりません.