泛型协变和抗变

/*
泛型协变和抗变
.net 4.0增加的特性
参数是可以协变的
方法返回类型是抗变的
*/

namespace Frank
{
	public class Test
    {
        public static void Main(string[] args)
        {
			Rectangle s = new Rectangle();
			Rectangle r = new Rectangle();
			r.Set(s);//协边,需要基类型,但是可以传递子类型的引用,总是隐士的。
			//Rectangle r2 =  r.Get();//抗变,需要显示。因为返回的父类型不一定总是子类型中的Rectangle类型

			Rectangle r3 = new Rectangle();
			System.Console.WriteLine(r3[0]);//访问索引器


			
        }
    }
	public class Shape
	{
		public double Width{get;set;}
		public double Height{get;set;}
		public override string ToString()
		{
			return string.Format("Width:{0},Height:{1}",Width,Height);
		}
	}
	public class Rectangle : Shape
	{
		public void Set(Shape s)
		{
			
		}
		public Shape Get()
		{
			return new Shape{Width=20,Height=10};
		}
		public  Rectangle this[int index]//自定义索引器
		{
			get
			{
				return new Rectangle{Width=1,Height=2};
			}
		}
	}
	public interface Test2<out T>//定义一个泛型接口,用out声明是协变的 返回输出类型只能是T类型
	{
		T this[int index]{get;}
	}
	public interface Test3<in T>//定义一个泛型接口,用in声明是抗变的,只能把T类型作为方法的输入类型
	{
		void Show(T show);
	}

  

posted on 2013-11-25 16:03  wp456  阅读(225)  评论(0)    收藏  举报

导航