首先,声明一个Currency的结构。Currency结构有自己的ToString()重载方法和一个与GetCurrencyUnit()的签名相同的静态方法。这样,就可以用同一个委托变量调用这些方法了:
struct Currency
{
public uint Dollars;
public ushort Cents;
public Currency(uint dollars, ushort cents)
{
this.Dollars = dollars;
this.Cents = cents;
}
public override string ToString()
{
return string.Format("${0}.{1,-2:00}", Dollars, Cents);
}
public static string GetCurrencyUnit()
{
return "Dollar";
}
public static explicit operator Currency(float value)
{
checked
{
uint dollars = (uint)value;
ushort cents = (ushort)((value - dollars) * 100);
return new Currency(dollars, cents);
}
}
public static implicit operator float(Currency value)
{
return value.Dollars + (value.Cents / 100.0f);
}
public static implicit operator Currency(uint value)
{
return new Currency(value, 0);
}
public static implicit operator uint(Currency value)
{
return value.Dollars;
}
}
下面就是GetString实例,代码如下:
private delegate string GetAString();
static void Main()
{
int x = 40;
GetAString firstStringMethod = x.ToString;
Console.WriteLine("String is {0}", firstStringMethod());
Currency balance = new Currency(34, 50);
// firstStringMethod references an instance method
firstStringMethod = balance.ToString;
Console.WriteLine("String is {0}", firstStringMethod());
// firstStringMethod references a static method
firstStringMethod = new GetAString(Currency.GetCurrencyUnit);
Console.WriteLine("String is {0}", firstStringMethod());
}
这段代码说明了如何通过委托调用方法,然后重新给委托指定在类的不同实例上的引用的不同方法,甚至可以指定静态方法,或者在类的不同类型的实例上引用的方法。只要每个方法的签名匹配委托定义即可。
运行上面的程序,会得到委托引用的不同方法的输出结果:
String is 40
String is $34.50
String is Dollar
但是,我们实际上还没有说明把一个委托传递给另外一个方法的具体过程,也没有得到任何特别有用的结果。调用int和Currency对象的ToString()的方法要比使用委托直观的多!!! 但是,需要用一个相当复杂的的示例来说明委托的本质,才能真正领悟到委托的用处。等到下一节,书中就会给出两个委托的示例。第一个示例仅使用委托调用两个不同的操作。他说明了如何把委托传递给方法,如何使用委托数组,但是这仍然没有很好的说明:没有委托,就不能完成很多工作。第二个示例就复杂得多了,它有一个类BubbleSorter,这个类实现了一个方法,按照升序排列一个对象数组。没有委托是很难编写出这个类的!!!(详见下一节)
C#高级编程(第8版)——委托声明、使用(第一节),布布扣,bubuko.com
原文:http://www.cnblogs.com/hoohau/p/3814952.html