1. 抽象类:

     

public abstract class Calculator<T>

{

public abstract T Add(T a, T b);

}

  1. 为int建立一个具体的类:

namespace Int32

{

public class Calculator: FhWeb.Generic_Calculator.Calculator<int>

{

public override int Add( int a , int b )

{

return a + b;

}

}

}

  1. 建立一个算法类,用来执行数据与计算类的关联:

     

public class AlgorithmLibrary<T> where T:new()

{

Calculator<T> calculator;

 

public AlgorithmLibrary( Calculator<T> calculator)

{

this.calculator = calculator;

}

 

public T Sum(List<T> items)

{

T sum = new T();

for (int i = 0; i < items.Count; i++)

{

sum = calculator.Add(sum, items[i]);

}

 

return sum;

 

}

}

  1. 测试:

     

protected void Page_Load(object sender, EventArgs e)

{

List<int> list = new List<int>();

for (int i = 1; i <= 100; i++)

{

list.Add(i);

}

 

AlgorithmLibrary<int> library = new AlgorithmLibrary<int>(new Int32.Calculator());

int result = library.Sum(list);

Response.Write(result);

}

 

输出结果为:5050

说明执行正确了

 

  1. 说明

这里面用到的List类是System.Collections.Generic.List类,所以在类文件中要引用相应的命名空间。

posted on 2007-06-14 13:45  今夜太冷  阅读(366)  评论(0)    收藏  举报