如果泛型类型用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();
}
}
Rec.getrec()方法返回一个实现Index<rectangle>接口的rec类,可以把返回值赋予Index<rectangle>类型的变量rectangle.接口是协变的,所以可以把返回值赋予Index<shape>类型的变量。使用shapes变量可以在for循环中使用接口的索引器和Count属性。 |