1. 程式人生 > >介面的協變與抗變

介面的協變與抗變

一,泛型介面中泛型型別的前面標有in和out關鍵字 其中標有out關鍵字的引數我協變,而輸出的結果就是抗變,IN與之相反。

如下程式碼:

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

namespace KongzhiTai
{
class Program
{
static void Main(string[] args)
{
//IIndex<Rectangle> rectangles = RectangleCollection.Getrectangles();//
//IIndex<Shape> shapes = rectangles;
//for (var i = 0; i < shapes.Count; i++)
//{
// Console.WriteLine(shapes[i]);
//}
//Console.ReadKey();
Rectangle re = new Rectangle();
re.Heigh = 11;
re.Width = 11;
Console.WriteLine(re);
Console.ReadKey();

}

}

//建立實現介面 IIndex的RectangleCollection類
public class RectangleCollection:IIndex<Rectangle>
{
//建立rectangle集合
private readonly Rectangle[] _data = new Rectangle[3] {
new Rectangle{Heigh=11,Width=11},
new Rectangle{Heigh=22,Width=22},
new Rectangle{Heigh=33,Width=33}
};
public static RectangleCollection Getrectangles()
{
return new RectangleCollection();
}
public Rectangle this[int index]
{
get { return _data[index]; }
}
//建立的rectangle的長度
public int Count
{
get { return _data.Length; }
}
}
//如果泛型型別用out關鍵字標註,泛型介面就是協變的。這也意味著返回型別只能是T
public interface IIndex<out T>
{
T this[int index]{get;}//返回值是T型別的索引器
int Count { get; }//Count屬性
}
public class Shape
{
public double Heigh { get; set; }
public double Width { get; set; }
public override string ToString()
{
return string.Format("Width:{0},Height:{1}", Width.ToString(), Heigh.ToString());
}

}
public class Rectangle:Shape
{

}

}