Hello
Imagine delegates as function pointers - you can pass this pointer to a
class which will be able to call this function (a callback) without
knowing about the class that contains the function or any implementation
details.
I have written a method that browses a tree recursively. I need to do
this from a lot of different classes, so I've put that code in a single
method that takes a callback handler. I'm traversing the tree and call
the delegate for every node:
public static void BrowseNodes(TreeNodeCollection nodes,
ClassNodeHandler callbackHandler)
{
foreach (TreeNode node in nodes)
{
ClassNode classNode = node as ClassNode;
if (classNode != null)
{
callbackHandler(classNode);
}
//call recursively
BrowseNodes(node.Nodes, callbackHandler);
}
}
All I have to do now is to create a delegate and pass it along with the
nodes to inspect:
//event handler in a gui
public void OnChangeColor()
{
NodeUtil.BrowseNodes(tree.Nodes, new ClassNodeHandler(ChangeColor));
}
//the callback handler
private void ChangeColor(ClassNode node)
{
node.ForeColor = ...
}
hth, Philipp