Aquí hay un ejemplo simple que muestra cuán útiles pueden ser los delegados para crear código simple que siga el principio DRY. También le permite mantener el código extremadamente cerca de donde se necesita.
Action<Button, Action<Button>> prepareButton =
(btn, nxt) => {
btn.Height = 32;
btn.Width= 64;
nxt(btn);
};
prepareButton(myBtn1, btn => btn.Text = "A");
prepareButton(myBtn2, btn => btn.Text = "B");
prepareButton(myBtn3, btn => btn.Text = "C");
Aquí hay un ejemplo del mundo real de la ventaja que brindan los delegados.
protected override void PageInitialize()
{
const string selectCodeFormat = "javascript:selectCode('{0}', '{1}');";
const string onClick = "return toggleElement(this);";
Func<HtmlGenericControl> getElement = null;
Action<HtmlGenericControl> setElement = null, addChild = null;
HtmlGenericControl level1Element = null, level2Element = null, level3Element = null, level4Element = null;
string className = null, code = null, description = null;
using (var records = Core.Database.ExecuteRecords("code.SocCodeTree"))
{
while (records.Read())
{
code = records.GetString("Code");
description = records.GetString("Description");
if (records.GetString("Level4") != "")
{
className = "Level4";
setElement = e => level4Element = e;
getElement = () => level4Element;
addChild = e => level3Element.Controls.Add(e);
}
else if (records.GetString("Level3") != "")
{
className = "Level3";
setElement = e => level3Element = e;
getElement = () => level3Element;
addChild = e => level2Element.Controls.Add(e);
}
else if (records.GetString("Level2") != "")
{
className = "Level2";
setElement = e => level2Element = e;
getElement = () => level2Element;
addChild = e => level1Element.Controls.Add(e);
}
else
{
className = "Level1";
setElement = e => level1Element = e;
getElement = () => level1Element;
addChild = e => Root.Controls.Add(e);
}
var child = new HtmlGenericControl("li");
child.Attributes["class"] = className;
var span = new HtmlGenericControl("span") {
InnerText = code + " - " + description + " - "
};
span.Attributes["onclick"] = onClick;
child.Controls.Add(span);
var a = new HtmlAnchor() {
InnerText = "Select",
HRef = string.Format(selectCodeFormat, code, description)
};
child.Controls.Add(a);
setElement(new HtmlGenericControl("ul"));
child.Controls.Add(getElement());
addChild(child);
}
}
}