C# Delegate 委托(下)

今天剛好遇到一個委托的問題,寫下來跟大家分享

書上有提到類似的問題所以就把書裡的例子改一改。假如我們今天要做 Bubble sort 但我們想動態改變排序的方式, C++ 而言會傳入 function pointer 而 C# 會使用委託:

using System;

namespace DotNetCoreTest
{
    class Program
    {
        public delegate bool Comparesion(int first, int second);

        // sort with different comparesion
        public static void BubbleSort(ref int[] arr, 
                                      Comparesion compare)
        {
            int tmp = 0;

            for(int i = 1; i < arr.Length; ++i)
            {
                for (int j = 0; j < arr.Length; ++j)
                {
                    if (compare(arr[i],arr[j]))
                    {
                        tmp = arr[i];
                        arr[i] = arr[j];
                        arr[j] = tmp;
                    }
                }
            }
        }

        // compare method
        public static bool AscendSort(int a, int b)
        {
            if (a < b)
                return true;
            else
                return false;
        }

        static void Main(string[] args)
        {
            int[] arr = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
            
            BubbleSort(ref arr, AscendSort);

            foreach (int num in arr)
            {
                System.Console.Write($"{num} ");
            }
            System.Console.WriteLine();
        }
    }
}

我們把程式做點小修改,下面的程式是一個錯誤的示範:

static void Main(string[] args)
{
    int[] arr = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
            
    Func<int, int, bool> CompareMethod = AscendSort;

    BubbleSort(ref arr, CompareMethod);

    foreach (int num in arr)
    {
        System.Console.Write($"{num} ");
    }
    System.Console.WriteLine();
}

即便 Function 的結構相通也不能轉換成 Comparesion

最後來個有趣的小問題:

static void Main(string[] args)
{
    int[] arr = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
    Func<int, int, bool> CompareMethod = (int a, int b) 
                                        => { return a < b; };
    
    BubbleSort(ref arr, CompareMethod);
    BubbleSort(ref arr, (int a, int b) => { return a < b; });
    
    foreach (int num in arr)
    {
        System.Console.Write($"{num} ");
    }
    System.Console.WriteLine();
}

看出其中的差異了嗎?

留言

熱門文章