标题: 泛型接口的协变 [打印本页] 作者: 黄冉 时间: 2012-12-4 08:51 标题: 泛型接口的协变 如果泛型类型用out关键字标注,泛型接口就是协变的。也就是说返回类型只能为T
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 interface Index<out T>
{
T this[int index] { get; }
int Count { get; }
}//对接口Index使用了只读所引器。
public class Rec : Index<rectangle>
{
private rectangle[] data = new rectangle[3]
{
new rectangle{width=5,height=3.3},
new rectangle{width=2,height=3},
new rectangle{width=1.1,height=1.2}
};
public static Rec getrec()
{
return new Rec();
}
public rectangle this[int index]
{
get
{
if (index < 0 || index > data.Length)
throw new ArgumentOutOfRangeException("index");
return data[index];
}
}
public int Count
{
get
{
return data.Length;
}
}
}
class Program
{
static void Main(string[] args)
{
Index<rectangle> rectangles = Rec.getrec();
Index<Shape> shapes = rectangles;
for (int i = 0; i < shapes.Count; i++)
{
Console.WriteLine(shapes[i]);
}
Console.ReadKey();
}