委托(Delegate)

1.委托的学习

2.委托的举例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegatezDemo
{
    public delegate bool ComparisonHandler(int first, int second);

    public class DelegateSample
    {
        /// <summary>
        /// 升序排列
        /// </summary>
        /// <param name="items"></param>
        /// <param name="comparisonMethod"></param>
        public static void BubbleSort(int[] items,ComparisonHandler comparisonMethod)
        {
            int i;
            int j;
            int temp;
            if (comparisonMethod == null)
            {
                throw new ArgumentNullException("comparisonMethod");
            }
            if (items == null)
            {
                Console.WriteLine("{0} is null", items);
                return;
            }
            for (i = items.Length - 1; i >= 0; i-- )
            {
                for (j = 1; j <= i; j++)
                {
                    //if (items[j -1] > items[j])
                    if (comparisonMethod(items[j - 1],items[j]))
                    {
                        temp = items[j - 1];
                        items[j - 1] = items[j];
                        items[j] = temp;
                    }
                    
                }
            }
        }
        public static bool GreaterThan(int first, int second)
        {
            return first > second;
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegatezDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int i;
            int[] items = new int[5];
            for (i = 0; i < items.Length;i++ )
            {
                Console.Write("Enter an integer: ");
                items[i] = int.Parse(Console.ReadLine());
            }
            DelegateSample.BubbleSort(items, DelegateSample.GreaterThan);
            for (i = 0; i < items.Length;i++)
            {
                Console.WriteLine(items[i]);
            }
            Console.ReadKey();
        }
    }
}
原文地址:https://www.cnblogs.com/gylhaut/p/5745962.html