不装箱调用显示实现接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 不装箱调用显示实现接口
{
    class Program
    {
        static void Main(string[] args)
        {

            //此方法可以调用结构显示实现的方法,而避免装箱
            DisposableStruct ds = new DisposableStruct(); //结构的new 不会在堆上分配空间,会在栈上分配空间
            DisposableStruct.test<DisposableStruct>(ds);
            Console.ReadLine();
        }
    }

    public struct DisposableStruct : IDisposable
    {
      public  static void test<T>(T obj) where T : IDisposable {
            obj.Dispose();
        }

      // IDisposable ds=new DisposableStruct();
      //  ds.Dispose()  使用接口实例化结构然后调用显示实现的该方法,会造成装箱
      //结构显示实现接口的方法,必须要使用接口来实例化,结构转成接口类型需要装箱,如 IDisposable ds=new DisposableStruct();
        void IDisposable.Dispose() { Console.WriteLine("IDisposable.Dispose"); } 
    }
}

 

posted @ 2017-03-24 16:18  甜菜波波  阅读(151)  评论(0编辑  收藏  举报