Maybe it's just me, but this page only describes the syntax of a delegate, not the use of it. —Crusha 03:16, 23 May 2010 (UTC)
You mean examples? I have to admit that most of the time you should probably just use an object reference to call functions. However, there are special cases where delegates can be very handy, basically any case where you need a callback without imposing any restrictions on which object contains the callback function. Consider this example: You want to sort an array of PRIs by various criteria and reuse this sorting algorithm in multiple areas of your code, but with different ordering criteria. Without delegates you would have to implement the sorting function multiple times or provide new classes with a function to specify the ordering criteria. With delegates you can do it like this:
/** Return true if A comes before B. */ delegate bool PRIOrder(PlayerReplicationInfo A, PlayerReplicationInfo B); // could also return int -/0/+ to tell whether A comes before/is equal to/comes after B /** Sort a PRI array with user-specified ordering criteria. */ static function SortPRIs(out array<PlayerReplicationInfo> PRIArray, delegate<PRIOrder> InOrder) { local int n, i; local bool bSwapped; local PlayerReplicationInfo tmp; // bubble sort for simplicity do { bSwapped = False; for (i = 0; i < PRIArray.Length - 1; ++i) { if (!InOrder(PRIArray[i], PRIArray[i + 1]) { tmp = PRIArray[i]; PRIArray[i] = PRIArray[i + 1]; PRIArray[i + 1] = tmp; bSwapped = True; } } } until (!bSwapped); }
Sorting by score is easy now:
function bool ByScore(PlayerReplicationInfo A, PlayerReplicationInfo B) { return A.Score >= B.Score; } SortPRIs(PRIs, ByScore); // PRIs is now sorted from highest to lowest score
—Wormbo 10:15, 23 May 2010 (UTC)