2014-03-19 164 views
0

我有一個窗口有多個單選按鈕:第一組排序算法和第二個方向(升序,降序)。傳遞委託參數給MethodInfo.Invoke

每一個排序的方法,我有載:

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

回答

2

嘗試

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

例外:類型的對象 'System.Object的[]' 不能被轉換爲類型 'Lab2.SortingMethods.ComparatorUtil + ComparatorDelegate'。 sortMethod.Invoke中的 –

+0

?不可能是真的。傳遞給排序方法的參數是numbersToSort和ComparatorDelegate實例。所以sortMethod.Invoke將int和[]和新的ComparatorDelegate()的權利作爲null和object []。 – lavrik

+0

對不起,我的壞..它像你說的那樣工作!謝謝您的回答。 –