*申明,本文引自 《Accelarated C# 2008》一书 废话不多说,直接看例子
using System;
using System.Collections.Generic;
public interface IShape
{
double Area
{
get;
}
}
public class Circle : Ishape
{
public Circle(double radius)
{
this.radius = radius;
}
public double Area
{
get
{
return 3.1415 * radius* radius
}
}
private double radius;
}
public class Rect : IShape
{
public Rect(double width,double height)
{
this.width = width;
this.height = height;
}
public double Area
{
get
{
return width * height;
}
}
private double width;
private double height;
}
public class Shapes
{
public double TotalArea
{
get
{
double acc = 0
{
forearch(T shape in shapes)
{
acc +=shape.Area;
}
return acc;
}
}
public void add(T shape)
{
shapes.Add( shape);
}
private List
}
-----------------------以下是测试类-----------------------------
public class EntryPoint
{
static void Main()
{
Shapes
shapes.Add(new Circle(2));
shapes.Add(new Rect(3,5));
Console.WriteLine("Total Area :{0}",shapes.TotalArea);
}
}
测试类的目的是计划出Rect,Circle两个面积数字之和,可是这段代码编译不会通过,因为在实列化Circle,Rect的时候,泛型并不知道Area属性的存在,必须实现Contact,代码可修改为
public double TotalArea
{
get
{
double acc = 0 ;
{
forearch(T shape in shapes)
{
IShape theShape =(IShape) shape;//加上结口实现
acc +=shape.Area;
} return acc;
}
}
为了确保T类型都有Area属,可以在类定义时就加上Contact,写法为 public class Shapes