【问题标题】:Passing delegate parameter to MethodInfo.Invoke将委托参数传递给 MethodInfo.Invoke
【发布时间】:2014-03-19 16:50:20
【问题描述】:

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

我拥有的每个排序方法都包含:

 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);

【问题讨论】:

    标签: c# reflection delegates


    【解决方案1】:

    试试

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

    【讨论】:

    • 异常:“System.Object[]”类型的对象无法转换为“Lab2.SortingMethods.ComparatorUtil+ComparatorDelegate”类型。
    • 在 sortMethod.Invoke 中?不可能是真的。您传递给排序方法的参数是 numbersToSort 和 ComparatorDelegate 实例。所以 sortMethod.Invoke 取 null 和 object[] 与 int[] 和 new ComparatorDelegate() 对。
    • 对不起,我的错......它就像你说的那样工作!谢谢你的回答。
    • 欢迎您,@IulianRosca
    猜你喜欢
    • 2012-07-12
    • 1970-01-01
    • 2015-07-07
    • 2011-03-07
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 2021-10-23
    相关资源
    最近更新 更多