委托和Lambda表达式(一):委托概述

简述:

   委托,这个概念在我的脑海中的印象不是很深,但在实际的工作中还是常常用到的。为了系统的了解委托,我利用一段时间对委托做一些研究,并作一些笔记,以作为参考和理解。

委托概述:

  委托时一种定义方法签名的类型,用于将方法作为参数传递给其他的方法。事件处理程序就是通过委托调用的方法。

  为了更好的理解委托的用法,用冒泡排序的算法作为例子。

代码
namespace BubbleSort
{
public class BubbleSort
{
public enum SortType
{
Ascending,
Desecending
}

public static void BubbleSortMethod(int[] items, SortType sortType)
{
int i = 0;
int j = 0;
int temp = 0;

if (items == null) {
return;
}

for (i = items.Length - 1; i >= 0; i--) {
for (j = 0; j <= i; j++) {
switch (sortType) {
case SortType.Ascending:
if (items[j - 1] > items[j]) {
temp
= items[j - 1];
items[j
- 1] = items[j];
items[j]
= temp;
}
break;
case SortType.Desecending:
if (items[j - 1] < items[j]) {
temp
= items[j - 1];
items[j
- 1] = items[j];
items[j]
= temp;
}
break;
default:
break;
}
}
}
}
}
}

  上面程序只考虑了降序和升序的排序方式,倘若想要按字母、随机或按其他方式进行排列, BubbleSart() 方法和 SortType 值的数量就会很多,为了减少代码的重复,可以采用将比较方法作为一个参数传给 BubbleSort() 方法。

代码
namespace BubbleSort
{
public delegate bool ComparisonHandler(int first, int second); //声明委托

public class DelegateSample
{
public static void BubbleSortMethod(int[] items, ComparisonHandler comparisonMethod)
{
int i = 0;
int j = 0;
int temp = 0;

if (items == null) {
return;
}

if (comparisonMethod == null) {
throw new ArgumentNullException("comparisonMethod");
}

for (i = items.Length - 1; i >= 0; i--) {
for (j = 1; j <= i; j++) {
//委托方法
if (comparisonMethod(items[j - 1], items[j])) {
temp
= items[j - 1];
items[j
- 1] = items[j];
items[j]
= temp;
}
}
}
}

public static bool GreayerThan(int first, int second)
{
return first > second;
}
}
}

   委托实例与类相似,通过new关键字进行实例化。实例化的过程如下:

代码
namespace BubbleSort
{
class Program
{
static void Main(string[] args)
{
int[] items = new int[100];

Random random
= new Random();
for (int i = 0; i < items.Length; i++) {
items[i]
= random.Next(int.MinValue, int.MaxValue);
}

DelegateSample.BubbleSortMethod(items, DelegateSample.GreayerThan);

for (int i = 0; i < items.Length; i++) {
Console.WriteLine(items[i]);
}

Console.ReadLine();
}
}
}
原文地址:https://www.cnblogs.com/muzihai1988/p/1926925.html