Reputation: 1015
I have a window with multiple radio buttons : first group Sorting Algorithms and second directions (Ascending, Descending).
Every Sorting Method that I have contains :
public delegate bool ComparatorDelegate(int a, int b);
public static int[] sort(int[] array, ComparatorDelegate comparator){...}
and I mention that I need to keep this signatures (specially passing a delegate as a parameter).
Now the problem is , I have two methods
First one retrieves the selected algorithm
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);
}
}
and the second one retrieves the direction :
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'.
something like this :
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);
Upvotes: 0
Views: 1167
Reputation: 1474
Try
Object[] parameters = new Object[]
{ numbersToSort, new ComparatorDelegate (selectedDirectionComparator)};
Upvotes: 2