Sunwayking

导航

C# 浅拷贝与深拷贝

    struct Class1: ICloneable
    {
        [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.I4, SizeConst = 2)]
        public int[] lpAlarmPoints;

        /// <summary>
        /// 深拷贝Clone
        /// </summary>
        /// <returns></returns>
        public object Clone()
        {
            Class1 newObj = new Class1();
            newObj.lpAlarmPoints = new int[lpAlarmPoints.Length];
            Array.Copy(lpAlarmPoints, newObj.lpAlarmPoints, lpAlarmPoints.Length);
            return newObj;
        }

        ///// <summary>
        ///// 浅拷贝Clone
        ///// </summary>
        ///// <returns></returns>
        //public object Clone()
        //{
        //    return this.MemberwiseClone();
        //}
    }

  

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Class1 c1 = new Class1();
            c1.lpAlarmPoints = new int[] { 2, 2 };

            /*Clone - 可浅可深,当前是深拷贝*/
            var t = (Class1)c1.Clone();
            t.lpAlarmPoints[0]=0;

            /*赋值 - 浅拷贝*/
            //var t = c1;
            //t.lpAlarmPoints[0] = 0;

            /*函数参数传递1 - 浅拷贝*/
            //test1(c1);

            /*函数参数传递2 - 浅拷贝*/
            //test2(ref c1);
            
        }
        void test1(Class1 input)
        {
            input.lpAlarmPoints[0]=0;
        }
        void test2(ref Class1 input)
        {
            input.lpAlarmPoints[0] = 0;
        }
    }

  

posted on 2013-02-20 14:10  Sunwayking  阅读(313)  评论(0编辑  收藏  举报