delegate
// 可以接受若干参数的委托
public delegate double Method( params int[] numbers);
public class Demo
{
public double Times( params int[] numbers)
{
double result = 1;
foreach (int i in numbers)
result *= i;
return result;
}
public double Div(params int[] numbers)
{
if (numbers == null || numbers.Length == 0)
throw new InvalidOperationException("参数错误");
if (numbers.Length == 1)
return numbers[0];
double first = numbers[0];
int length = numbers.Length;
for (int i = 1; i < length; i++)
{
int x = numbers[i];
if (x == 0)
throw new InvalidOperationException("错误的参数");
first /= x;
}
return first;
}
}
public class Calculator
{
public Method Times;
public Method Div;
public Calculator()
{
}
public double MyTimes(params int[] numbers)
{
return this.Times(numbers);
}
public double MyDiv(params int[] numbers)
{
return this.Div(numbers);
}
}
class Program
{
static void Main(string[] args)
{
// 装配
Calculator calculator = new Calculator();
Demo demo = new Demo();
calculator.Times = demo.Times;
calculator.Div = demo.Div;
// 使用计算器
double r = calculator.MyTimes(1, 2, 3, 4);
Console.WriteLine(r);
double r2 = calculator.MyDiv(12, 2, 3);
Console.WriteLine(r2);
}}
posted on 2011-09-06 13:49 乔乔lovefreedom 阅读(301) 评论(0) 编辑 收藏 举报