我有一个带有多个单选按钮的窗口:第一组排序算法和第二个方向(升序,降序)。
我所包含的每种排序方法:
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);
答案 0 :(得分:2)
尝试
Object[] parameters = new Object[]
{ numbersToSort, new ComparatorDelegate (selectedDirectionComparator)};