c# 委托

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace 委托与事件处理_c_____

{

    //委托最常见的用法就是用作回调执行所需任务的方法

    //想创建委托,只需使用关键字new创建一个委托类型的新实例,将方法名称作为参数传递即可

    //声明委托实例:public delegate void OpDelegate(...)

    public class BubbleSort

    {

        //例子。对数组冒泡排序,比较方法为委托,在类外定义

        public delegate bool Order(object first, object second);

 

        public void Sort(Array table, Order sortHandler)

        { 

            if(sortHandler == null)

                throw new ArgumentNullException();

 

            bool nothingSwapped = false;

            int pass = 1;

            while(nothingSwapped == false)

            {

                nothingSwapped = true;

                for(int index = 0;index < table.Length-pass;++index)

                {

                    //用一个 Order 委托确认排序顺序

                    if (sortHandler(table.GetValue(index), 

                        table.GetValue(index + 1)) == false)

                    {

                        nothingSwapped = false;

                        object temp = table.GetValue(index);

                        table.SetValue(table.GetValue(index + 1), index);

                        table.SetValue(temp, index + 1);

                    }

                }

                ++pass;

            }

 

        }

    }

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 委托与事件处理_c_____
{
    class DelegateSortApp
    {
        static int[] sortTable = { 5, 4, 6, 8, 2 };
        static void Main(String[] args)
        {
            DelegateSortApp app = new DelegateSortApp();
            //按原来顺序打印数组
            foreach (int i in sortTable)
                Console.WriteLine(i);
            Console.WriteLine("Sorting");
            BubbleSort sorter = new BubbleSort();//创建
            BubbleSort.Order order = new BubbleSort.Order(SortOrder);//写入委托
            sorter.Sort(sortTable, order);//这里调用到委托
            foreach (int i in sortTable)
                Console.WriteLine("Done");
        }
        //委托方法,由用户自己实现
        static public bool SortOrder(object first, object second)
        {
            int f = (int)first;
            int s = (int)second;
            return f < s;
        }
    }
}
委托:很好的封装了类,将具体的实现交给用户,对于类的设计很有用。接下来将讨论事件

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值