委托是函数的封装,它代表一“类”函数。他们都符合一定的签名:拥有相同的参数列表、返回值类型。同时委托也可以看作是对函数的抽象,是函数的“类”。此时,委托是实例代表一个具体的函数。
public
class
Book

...
...
{
public delegate double GetPrice(Book b);
private string name;

public string Name

......{

get ......{ return name; }

set ......{ name = value; }
}
private double price;

public double Price

......{

get ......{ return price; }

set ......{ price = value; }
}
}
public
class
WinterRebate

...
...
{
public static double Cal(Book b)

......{
return b.Price * 0.8;
}
}
public
class
SummerRebate

...
...
{
public static double Cal(Book b)

......{
return b.Price * 0.9;
}
}
static
void
Main(
string
[] args)

...
...
{
Book b = new Book();
b.Price=100;
Book.GetPrice g;
if (Console.ReadLine() == "win")

......{
g = new Book.GetPrice(WinterRebate.Cal);
}
else

......{
g = new Book.GetPrice(SummerRebate.Cal);
}

Console.WriteLine(g(b));
}
现定义一个书类,其中定义了价格,随着季节的改变可能有不同的折扣,希望可以灵活替换折扣
public
class
Book
...
...
{
public delegate double GetPrice(Book b);
private string name;
public string Name
......{
get ......{ return name; }
set ......{ name = value; }
}
private double price;
public double Price
......{
get ......{ return price; }
set ......{ price = value; }
}
}
public
class
WinterRebate
...
...
{
public static double Cal(Book b)
......{
return b.Price * 0.8;
}
}
public
class
SummerRebate
...
...
{
public static double Cal(Book b)
......{
return b.Price * 0.9;
}
}
static
void
Main(
string
[] args)
...
...
{
Book b = new Book();
b.Price=100;
Book.GetPrice g;
if (Console.ReadLine() == "win")
......{
g = new Book.GetPrice(WinterRebate.Cal);
}
else
......{
g = new Book.GetPrice(SummerRebate.Cal);
}
Console.WriteLine(g(b));
}
本文介绍了一种通过定义委托来实现不同季节书籍折扣策略的方法。通过创建`Book`类及两个静态类`WinterRebate`和`SummerRebate`来分别实现冬季和夏季的折扣计算。根据用户输入选择应用不同的折扣计算方式。
3257

被折叠的 条评论
为什么被折叠?



