装箱和拆箱的例子,value type的接口

来源:互联网 发布:电子秤数据采集工具 编辑:程序博客网 时间:2024/05/16 18:46

value type的接口是什么用的呢?应该怎么用?


using System;using NUnit.Framework;namespace ClassLibrary{    [TestFixture]    public class ClassLib    {        public interface IChange        {            void Change(Int32 x, Int32 y);        }        internal struct Point : IChange        {            private Int32 m_x, m_y;            public Point(int x, int y)            {                m_x = x;                m_y = y;            }            #region IChange Members            public void Change(int x, int y)            {                m_x = x;                m_y = y;            }            #endregion            public override string ToString()            {                return m_x + "," + m_y;            }        }        [Test]        public void MyTest()        {            var p = new Point(1, 1);            Console.WriteLine(p); //(1,1)            p.Change(3, 3); //change good            Console.WriteLine(p); //(3,3)            object o = p; //boxing p to o            ((Point) o).Change(4, 4); //unboxing to stack, so change happen on the stack            Console.WriteLine(o); //still (3,3)            ((IChange) p).Change(5, 5); //boxing the p to a object and after change finish, the p is GC            Console.WriteLine(p);            ((IChange) o).Change(6, 6);//所以说,value type的接口是用来修改他的装箱产物用的            Console.WriteLine(o);        }    }}


原创粉丝点击