类与类之间 相同属性及字段拷贝

本文介绍了一种用于不同类之间成员复制的方法,通过节省代码量提高效率。

主要是为了应付不同类之间成员的相互赋值。节省代码量。

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);
        }
    }

 

注意 类的名称必须相同,并且类型必须相同。

转载于:https://www.cnblogs.com/shikyoh/archive/2012/04/11/2442651.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值