格物致知--《Effective C#》读书笔记--验证接口引用指向装箱后的值类型时无需拆箱

来源:互联网 发布:office mac中文破解版 编辑:程序博客网 时间:2024/06/01 12:09

 

欲验证的结论:接口引用指向装箱后的值类型时无需拆箱


代码如下:


 interface SomeInterface

    {

        void MethodInInterface();

    }


    struct OneValueType : SomeInterface

    {

        public void MethodInInterface()

        {

            Console.WriteLine("get called");

        }

    }


    class TestUnBox

    {

        public static void Main()

        {

        }


        private static void CastStruct()

        {

            OneValueType ovt = new OneValueType();

            object o = ovt;//Box

            ((OneValueType)o).MethodInInterface();

        }


        private static void CastInterface()

        {

            OneValueType ovt = new OneValueType();

            object o = ovt;//Box

            ((SomeInterface)o).MethodInInterface();

 }

}


其中OneValueType是值类型,它实现了SomeInterface


两个方法CastStructCastInterface分别把装箱之后的值类型转型为OneValueTypeSomeInterface。预计的结果是第二个方法无需拆箱,查看IL来验证:


这是CastStruct():


 

这是CastInterface():


 

可见,第二个方法中没有unbox指令,结论得证。



2009729

 


原创粉丝点击