委托链
前面介绍过MulticastDelegate中有一个_prev的私有字段,这个字段指向另一个MulticastDelegate对象的引用,这样就实现了委托链(其实与我们在学链表时的实现方式是一致的)。
当委托链表被调用时,它首先会调用委托中在其前面的委托对象,这里如果被调的回调方法具有返回值,将被丢失,委托链只会返回最后一次调用回调方法的返回值。
委托示例
这是一个我自认为比较经典的委托示例(给排序算法传递一个动态比较的函数)。
using
System;
using
System.Collections.Generic;
using
System.Text;
namespace
MyDelegateTest
{
///<summary>
///
说明:给排序算法传递一个动态比较函数的委托示例
///
作者:文野
///
联系:stwyhm.cnblogs.com
///</summary>
//
进行排序的委托
public delegate bool Compare(int left, int right);
public class DelegateSample
{
private int[] items;
public int[] Items
{
set { items = value; }
get { return items; }
}
//
比大
public bool Greater(int left, int right)
{
return left > right;
}
//
比小
public bool Less(int left, int right)
{
return !Greater(left, right);
}
public void Sort(Compare compare)
{
for (int i = 0; i < items.Length-1; i++)
{
for (int j = i + 1; j < items.Length; j++)
{
if (compare(items[i], items[j]))
{
int tmp = items[i];
items[i] = items[j];
items[j] = tmp;
}
}
}
}
}
}
调用页面
using
System;
using
System.Data;
using
System.Configuration;
using
System.Collections;
using
System.Web;
using
System.Web.Security;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Web.UI.WebControls.WebParts;
using
System.Web.UI.HtmlControls;
using
MyDelegateTest;
public
partial class Sort : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
DelegateSample sample = new DelegateSample();
sample.Items = GetItems();
//
使用降序
sample.Sort(new Compare(sample.Less));
PrintItems(sample);
}
private void PrintItems(DelegateSample sample)
{
for (int i = 0; i < sample.Items.Length; i++)
{
Response.Write(sample.Items[i] + "<br/>");
}
}
private int[] GetItems()
{
string[] str = this.TextBox1.Text.Split(",".ToCharArray());
int[] items = new int[str.Length];
for (int i = 0; i < str.Length; i++)
items[i] = int.Parse(str[i]);
return items;
}
protected void Button2_Click(object sender, EventArgs e)
{
DelegateSample sample = new DelegateSample();
sample.Items = GetItems();
//
使用升序
sample.Sort(new Compare(sample.Greater));
PrintItems(sample);
}
}
效果图:
降序
升序