首先,聲明一個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,這個類實現了一個方法,按照升序排列一個對象數組。沒有委托是很難編寫出這個類的!!!(詳見下一節)