将委托参数传递给MethodInfo.Invoke

本文关键字:MethodInfo Invoke 参数传递 | 更新日期: 2023-09-27 17:50:55

我有一个带有多个单选按钮的窗口:第一组排序算法和第二个方向(升序,降序)。

所有的排序方法都包含:

 public delegate bool ComparatorDelegate(int a, int b);
 public static int[] sort(int[] array, ComparatorDelegate comparator){...}

,我提到我需要保持这个签名(特别是传递一个委托作为参数)。

现在的问题是,我有两个方法
第一个检索所选算法

private Type getSelectedSortingMethod()
    {
        if (radioButtonBubbleSort.Checked)
        {
            return typeof(BubbleSort);
        }
        else if (radioButtonHeapSort.Checked)
        {
             return typeof(HeapSort);
        }
        else if (radioButtonQuickSort.Checked)
        {
             return typeof(QuickSort);
        }
        else
        {
             return typeof(SelectionSort);
        }
    }

,第二个检索方向:

   private Func<int, int, bool> getSelectedDirection()
    {
        Func<int, int, bool> selectedDirectionComparator = null;
        if (radioButtonAscending.Checked)
        {
            selectedDirectionComparator = ComparatorUtil.Ascending;
        }
        else if (radioButtonDescending.Checked)
        {
            selectedDirectionComparator = ComparatorUtil.Descending;
        }
        return selectedDirectionComparator;
    }

Question : How can I invoke the sort method with a delegate parameter , because passing Func throws exception ?

Exception :
Object of type 'System.Func`3[System.Int32,System.Int32,System.Boolean]' cannot be converted to type 'Lab2.SortingMethods.HeapSort+ComparatorDelegate'.


像这样:

        Type sortingMethodClass = getSelectedSortingMethod();
        MethodInfo sortMethod = sortingMethodClass.GetMethod("sort");
        Func<int, int, bool> selectedDirectionComparator = getSelectedDirection();
        int[] numbersToSort = getValidNumbers();
        Object[] parameters = new Object[] {numbersToSort,selectedDirectionComparator};
        sortMethod.Invoke(null, parameters);
        displayNumbers(numbersToSort);

将委托参数传递给MethodInfo.Invoke

Try

 Object[] parameters = new Object[] 
   { numbersToSort, new ComparatorDelegate (selectedDirectionComparator)};