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

本文介绍委托的概念及其在编程中的应用,通过冒泡排序算法演示如何使用委托来传递比较方法,以实现灵活的排序方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

简述:

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

委托概述:

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

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

ContractedBlock.gifExpandedBlockStart.gif代码
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() 方法。

ContractedBlock.gifExpandedBlockStart.gif代码
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关键字进行实例化。实例化的过程如下:

ContractedBlock.gifExpandedBlockStart.gif代码
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/archive/2011/01/19/1926925.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值