之前看到一道关于值类型在装箱和拆箱上的题目,觉得很有意思,所以就拿出来分享一下
大家可以先用几分钟的时间在心里做个答案再往下看 这样或许帮助更大
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