Generic Delegate and IList<T>
I want to implement a delegate solution for Bubble sort. I have this code:
public delegate void SortHandler<T>(IList<T> t);
public static void Sort<T>(IList<T> arr, SortHandler<T> func)
{
fun开发者_StackOverflow社区c(arr);
}
int[] arr2 = { 10,1,2,3,4 };
CollectionHelper.Sort<int>(arr2, bubble_sort);
bubble sort function signature is:
static void bubble_sort(int[] array) {}
I get this error:
Argument '2': cannot convert from 'method group' to 'DelegatesAndGenerics.SortHandler
Yes - your bubble_sort method requires an int[] as the parameter, whereas SortHandler only specifies IList<T>. You can't create a SortHandler<int> from bubble_sort.
Just because you happen to be sorting an int[] doesn't mean CollectionHelper.Sort is guaranteed to call the delegate with an array instead of (say) a List<int>.
For example, consider this implementation:
public void Sort<T>(T[] array, SortHandler<T> handler)
{
List<T> list = new List<T>(array);
handler(list);
}
How would you expect that to cope if you'd managed to pass in the bubble_sort method as your handler?
The simplest solution is to change your bubble_sort method to accept IList<int> instead of just int[].
(This is a slightly strange situation though, I have to say. Usually the kind of handler you'd pass into a generic sort method would be something to compare any two elements - not to perform the actual sort itself.)
I think the issue is that your int[] isn't an IList. If you change your SortHandler delegate like so:
public delegate void SortHandler<T>(IEnumerable<T> t);
you should be able to use arrays, lists, or whatever you want.
加载中,请稍侯......
精彩评论