日期:2014-05-18  浏览次数:20970 次

C#装箱拆箱
我看c#本质论的时候有段关于装箱拆箱的主题看不懂,希望有人能解释下,
C# code
class Program
    {
        static void Main(string[] args)
        {
            Angle angle = new Angle(25, 58, 23);
            object objectAngle = angle;//Box
            Console.WriteLine(((Angle)objectAngle).Hours);

            //Unbox and discard
            ((Angle)objectAngle).MoveTo(26, 58, 23);
            Console.WriteLine(((Angle)objectAngle).Hours);

            //Box, modify and discard
            ((IAngle)angle).MoveTo(26, 58, 23);
            Console.WriteLine(((Angle)angle).Hours);

            //Modify heap directly
            ((IAngle)objectAngle).MoveTo(26, 58, 23);
            Console.WriteLine(((Angle)objectAngle).Hours);

            Console.ReadKey();
        }
    }

    struct Angle : IAngle
    {
        public Angle(int hours, int minutes, int seconds)
        {
            _Hours = hours;
            _Minutes = minutes;
            _Seconds = seconds;
        }

        private int _Hours;

        public int Hours
        {
            get
            {
                return _Hours;
            }
        }

        private int _Minutes;

        public int Minutes
        {
            get
            {
                return _Minutes;
            }
        }

        private int _Seconds;

        public int Seconds
        {
            get
            {
                return _Seconds;
            }
        }

        public Angle Move(int hours, int minutes, int seconds)
        {
            return new Angle(Hours + hours, Minutes + minutes, Seconds + seconds);
        }

        #region IAngle 成员

        public void MoveTo(int hours, int minutes, int seconds)
        {
            _Hours = hours;
            _Minutes = minutes;
            _Seconds = seconds;
        }

        #endregion
    }
控制台输出的是25,25,25,26.。。不懂为什么会这样。

------解决方案--------------------
把值类型转成object就是装箱啊
相反就是拆箱
int i = 123;
object o = (object)i; // boxing
 

o = 123;
i = (int)o; // unboxing
------解决方案--------------------
楼上正解