委托,称为匿名函数,允许您声明比较机制,而无需完全独立的函数,如下所示:
private void button1_Click(object sender, EventArgs e)
{
Things t1 = new Things();
t1.Item = "z";
Things t2 = new Things();
t2.Item = "a";
Things[] things = new Things[]{ t1, t2};
Array.Sort(things, CompareThings);
foreach(Things t in things)
{
Console.WriteLine(t.Item);
}
}
private int CompareThings(Things c1, Things c2)
{
return c1.Item.CompareTo(c2.Item);
}
Here's an example on MSDN 显示了一个排序的两个版本,一个带有匿名函数,一个带有声明函数(如上)。
作为旁注,c1.Item 与 c2.Item 的显式比较是必要的,因为 .Net 不知道它应该如何将一个“事物”实例与另一个进行比较。但是,如果您实现 IComparable 接口,那么您的代码会变得更简洁,因为您不需要匿名或单独的函数:
public class Things : IComparable<Things>
{
public string Item = "";
int IComparable<Things>.CompareTo(Things other)
{
return this.Item.CompareTo(other.Item);
}
}
接着是:
private void button1_Click(object sender, EventArgs e)
{
Things t1 = new Things();
t1.Item = "z";
Things t2 = new Things();
t2.Item = "a";
Things[] things = new Things[]{ t1, t2};
Array.Sort(things); // <-- the intenal implementation of CompareTo() we added to class Things will be used!
foreach(Things t in things)
{
Console.WriteLine(t.Item);
}
}