委托是函数的封装,它代表一“类”函数。他们都符合一定的签名:拥有相同的参数列表、返回值类型。同时委托也可以看作是对函数的抽象,是函数的“类”。此时,委托是实例代表一个具体的函数。
现定义一个书类,其中定义了价格,随着季节的改变可能有不同的折扣,希望可以灵活替换折扣
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;
}
}
... ... {
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 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));
}