装箱和拆箱

装箱和拆箱

  • 装箱:值类型转化为引用类型
  • 拆箱:引用类型转化为值类型
using System;
using System.Collections.Generic;
using System.Text;

internal interface IChangeBoxedPoint {
    void Change(Int32 x, Int32 y);
}
internal struct Point : IChangeBoxedPoint 
{
    private 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.ToString(), m_y.ToString());
    }
}
  public sealed  class Program
    {
        public  static void Main(string[] args)
        {
            Point p = new Point(1, 1);

            Console.WriteLine(p);//输出(1,1)

            p.Change(2, 2);
            Console.WriteLine(p);//输出(2,2)

            Object o = p;
            Console.WriteLine(o);//输出(2,2)

            ((Point)o).Change(3, 3);
            Console.WriteLine(o);//输出(2,2)

            ((IChangeBoxedPoint)p).Change(4, 4);
            Console.WriteLine(p);//输出(2,2)
            ((IChangeBoxedPoint)o).Change(5, 5);
            Console.WriteLine(o);//输出(5,5)
        }
    }

猜你喜欢

转载自blog.csdn.net/it_sharp/article/details/79880005