申明,本文引自 《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