日期:2014-05-18 浏览次数:20901 次
namespace func
{
class Program
{
static void Main(string[] args)
{
ProductN.DComputeTax d = new ProductN.DComputeTax(c => c * 0.1);
ProductN target = new ProductN() { Price = 200 };
target.dComputeTax = d;
double actual = target.ComputeTax();
Console.WriteLine(actual);
Console.Read();
}
}
class ProductN
{
public delegate double DComputeTax(double price);
public DComputeTax dComputeTax;
public double Price { get; set; }
public double ComputeTax()
{
return dComputeTax(Price);
}
}
}
namespace func
{
class Program
{
static void Main(string[] args)
{
//创建一个定义在ProductN类中的委托类型(DComputeTax )变量d
//创建委托变量时需要指定函数或匿名函数,在这段代码中使用的是匿名函数
//该匿名函数的功能是接受一个double参数,返回参数乘0.1
ProductN.DComputeTax d = new ProductN.DComputeTax(c => c * 0.1);
ProductN target = new ProductN() { Price = 200 };
//将构造好的委托变量赋给对象的字段dComputeTax
target.dComputeTax = d;
//调用对象的方法
double actual = target.ComputeTax();
Console.WriteLine(actual);
Console.Read();
}
}
class ProductN
{
public delegate double DComputeTax(double price);
public DComputeTax dComputeTax;
public double Price { get; set; }
public double ComputeTax()
{
//使用委托变量,实际就是调用在创建委托变量时指定的函数(返回十分之一)
return dComputeTax(Price);
}
}
}