代码改变世界

灵活的算法处理(委托学习系列二)

2012-02-16 13:53  秋日愚夫  阅读(174)  评论(0编辑  收藏  举报
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegateDEMO
{
public delegate int ArithmeticDelegate(int a , int b);

//根据传入的方法地址,进行计算
public class Arithmetic
{
private ArithmeticDelegate arithmeticOperate;
public ArithmeticDelegate ArithmeticOperate
{
get { return arithmeticOperate; }
set { this.arithmeticOperate = value; }
}

//在客户端没有传入方法之前,这个方法是不确定的
public int DoSomething(int a, int b)
{
return ArithmeticOperate(a, b);
}
}

//已经实现的具体方法
public class ArithmeticFounction
{
public int Add(int a, int b)
{
return a + b;
}

public int Sub(int a, int b)
{
return a - b;
}
}

class Program
{
static void Main(string[] args)
{
ArithmeticFounction af = new ArithmeticFounction();

Arithmetic a = new Arithmetic();
//将具体方法地址传入,则a可用传入方法进行运算了
a.ArithmeticOperate = new ArithmeticDelegate(af.Sub);
//DoSomething现在已经是Sub方法
int Result = a.DoSomething(20, 3);

Console.Write(Result.ToString());
Console.Read();
}
}
}