开发者论坛

 找回密码
 注册 (请使用非IE浏览器)
查看: 2865|回复: 0

[源码] 浅拷贝的一个简单例子

[复制链接]

0

精华

95

贡献

34

赞扬

帖子
101
软币
823
在线时间
98 小时
注册时间
2013-8-21
发表于 2015-1-7 09:28:27 | 显示全部楼层 |阅读模式
class Program
    {
        private static void Main(string[] args)
        {
            var p = new Person()
            {
                Name = "jxq",
                Age = 23
            };
            var shallowCopy = Operator<Person>.ShallowCopy(p);
            shallowCopy.Name = "feichexia";

            Console.WriteLine(shallowCopy.Name);
            Console.WriteLine(p.Name);

            Console.ReadKey();
        }

        public class Person
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }

        public static class Operator<T>
        {
            private static readonly Func<T, T> ShallowClone;

            public static T ShallowCopy(T sourcObj)
            {
                return ShallowClone.Invoke(sourcObj);
            }

            static Operator()
            {
                var origParam = Expression.Parameter(typeof (T), "orig");

                // for each read/write property on T, create a  new binding
                // (for the object initializer) that copies the original's value into the new object
                var setProps = from prop in typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
                    where prop.CanRead && prop.CanWrite
                    select (MemberBinding) Expression.Bind(prop, Expression.Property(origParam, prop));

                var body = Expression.MemberInit( // object initializer
                    Expression.New(typeof (T)), // ctor
                    setProps // property assignments
                    );

                ShallowClone = Expression.Lambda<Func<T, T>>(body, origParam).Compile();
            }
        }
    }
回复

使用道具 举报

Archiver|手机版|小黑屋|开发者网 ( 苏ICP备08004430号-2 )
版权所有:南京韵文教育信息咨询有限公司

GMT+8, 2024-5-13 17:29

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表