之前看到一道关于值类型在装箱和拆箱上的题目,觉得很有意思,所以就拿出来分享一下

大家可以先用几分钟的时间在心里做个答案再往下看 这样或许帮助更大

  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);

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

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

            Console.ReadKey();
        }
    }
    struct Point:IChangeBoxedPoint 
    {
        private int x, y;
        public Point(int x,int y)
        {
            this.x = x;
            this.y = y;
        }
        public void Change(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
        public override string ToString()
        {
            return string.Format("{0},{1}",x,y);
        }
    }
    interface IChangeBoxedPoint
    {
        void Change(int x,int y);
    }

下面是运行结果

1,1
2,2
2,2
2,2
2,2
5,5
结果

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-12
  • 2021-06-07
  • 2021-06-10
  • 2022-12-23
  • 2022-12-23
  • 2021-06-06
猜你喜欢
  • 2021-10-08
  • 2021-07-31
  • 2021-08-15
  • 2022-03-07
  • 2021-12-28
  • 2022-02-23
相关资源
相似解决方案