泛型接口

可变性和泛型接口

//IWrapper<T>接口定义了SetData和GetData方法
    interface IWrapper<T>
    {
        void SetData(T Data);
        T GetData();
    }
 //围绕指定的类型提供了一个简单的包装器(wrapper).
    class Wrapper<T> : IWrapper<T>
    {
        private T storedData;

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="data"></param>
        void IWrapper<T>.SetData(T data)
        {
            this.storedData = data;
        }

        /// <summary>
        /// 存储数据
        /// </summary>
        /// <returns></returns>
        T IWrapper<T>.GetData()
        {
            return this.storedData;
        }

        class Program
       {
                  static void Main(string[] args)
                  {
                        Wrapper<string> stringWrapper = new Wrapper<string>();
                        IWrapper<string> storedStringWrapper = stringWrapper;
                        storedStringWrapper.SetData("Hello World");
                         Console.WriteLine("存储的值是{0}",storedStringWrapper.GetData());
            Console.ReadLine();
                  }
     }

 协变接口

    class Wrapper<T> : IStoreWrapper<T>, IRetrieveWrapper<T>
    {
        private T storedData;

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="data"></param>
        void IStoreWrapper<T>.SetData(T data)
        {
            this.storedData = data;
        }

        /// <summary>
        /// 存储数据
        /// </summary>
        /// <returns></returns>
        T IRetrieveWrapper<T>.GetData()
        {
            return this.storedData;
        }
    }

   //IStoreWrapper<T>接口定义了SetData方法
    interface IStoreWrapper<T>
    {
        void SetData(T Data);
    }

    //IRetrieveWrapper<T>接口定义了GetData方法
    interface IRetrieveWrapper<T>
    {
        T GetData();
    }
    class Program
    {
        static void Main(string[] args)
        {
            Wrapper<string> stringWrapper = new Wrapper<string>();
            IStoreWrapper<string> storedStringWrapper = stringWrapper;
            storedStringWrapper.SetData("Hello World");
            IRetrieveWrapper<string> retrieveStringWrapper = stringWrapper;
            Console.WriteLine("存储的值是{0}", retrieveStringWrapper.GetData());
            Console.ReadLine();
        }
    }

只要存在从类型A到类型B的有效转换,或者类型A派生自类型B,就可以将一个IRetrieveWapper<B>引用

//协变性:如果泛型接口中的方法能返回字符串,它们也能返回对象。
//逆变形:如果泛型接口中的方法能获取对象参数,它们也能获取字符串参数,(用一个对象能执行的操作,用字符串同样能;因为所有字符串都是对象。)

原文地址:https://www.cnblogs.com/wuhuisheng/p/2876237.html