现在的位置: 首页 > 综合 > 正文

总结:CLR Via C#(第五章):值类型与引用类型——装箱和拆箱

2012年08月02日 ⁄ 综合 ⁄ 共 1799字 ⁄ 字号 评论关闭

struct

 class Program

    {

        static void Main(string[] args)

        {

            Point p = new Point(1, 1);

            Console.WriteLine(p);

 

            p.Change(2, 2);

            Console.WriteLine(p);

 

            object o = p;

            Console.WriteLine(o);

 

            ((Point)o).Change(3, 3);

            Console.WriteLine(o);

 

            p = (Point)o;

            p.Change(3, 3);

            Console.WriteLine(p);

        }

    }

 

    internal struct Point

    {

        Int32 m_x, m_y;

 

        public Point(Int32 x, Int32 y)

        {

            m_x = x;

            m_y = y;

        }

 

        public void Change(Int32 x, Int32 y)

        {

            m_x = x;

            m_y = y;

        }

 

        public override string ToString()

        {

            return string.Format("({0},{1})", m_x, m_y);

        }

    }

         输出:

 

Class

如果将Point改为Class类型,则输出:


 

Interface

    class Program

    {

        static void Main(string[] args)

        {

            Point p = new Point(1, 1);

            Console.WriteLine(p);

 

            p.Change(2, 2);

            Console.WriteLine(p);

 

            object o = p;

            Console.WriteLine(o);

 

            ((Point)o).Change(3, 3);

            Console.WriteLine(o);

 

            p = (Point)o;

            p.Change(3, 3);

            Console.WriteLine(p);

 

 

            ((IChangeBoxedPoint)p).Change(4, 4);

            Console.WriteLine(p);

 

            ((IChangeBoxedPoint)o).Change(5, 5);

            Console.WriteLine(o);

 

            Console.ReadLine();

        }

    }

 

    internal interface IChangeBoxedPoint

    {

        void Change(Int32 x, Int32 y);

    }

 

    internal struct Point:IChangeBoxedPoint

    {

        Int32 m_x, m_y;

 

        public Point(Int32 x, Int32 y)

        {

            m_x = x;

            m_y = y;

        }

 

        public void Change(Int32 x, Int32 y)

        {

            m_x = x;

            m_y = y;

        }

 

        public override string ToString()

        {

            return string.Format("({0},{1})", m_x, m_y);

        }

    }

 

输出:

 

抱歉!评论已关闭.