vendredi 12 février 2016

Call generic method c#

how to call generic method, I heard about reflection, but I think I'm doing some wrong, check please.

 public static LinkedListNode<T> MergeSortLL<T>(LinkedListNode<T> Head) where T : IComparable<T>
    {

        if (Head == null || Head.Next == null)
        {
            return Head;
        }
        LinkedListNode<T> middle = GetMiddle<T>(Head);
        LinkedListNode<T> half = middle.Next;
        middle.Next = null;

        return Merge(Head, half);

    }

And here i'm trying to invoke my generic method with parameters

    public void MSort()
    {
        Type type = typeof(MergeSort);
        MethodInfo method = typeof(MergeSort).GetMethod("MergeSortLL");
        MethodInfo generic = method.MakeGenericMethod(type);
        generic.Invoke(null, null);
    }

Update 2. Here more info what I've in my class MergeSort and why i'm using IComparable

class MergeSort
{

    public static LinkedListNode<T> MergeSortLL<T>(LinkedListNode<T> Head) where T : IComparable<T>
    {

        if (Head == null || Head.Next == null)
        {
            return Head;
        }
        LinkedListNode<T> middle = GetMiddle<T>(Head);
        LinkedListNode<T> half = middle.Next;
        middle.Next = null;

        return Merge(Head, Head, half);

    }

    public static LinkedListNode<T> Merge<T>(LinkedListNode<T> Head, LinkedListNode<T> Left, LinkedListNode<T> Right) where T : IComparable<T>
    {

        LinkedListNode<T> mHead = Head;
        LinkedListNode<T> curr = mHead;

        while (Left != null && Right != null)
        {
            if (Left.Value.CompareTo(Right.Value) <= 0)
            {
                curr.Next = Left;
                Left = Left.Next;
            }
            else
            {
                curr.Next = Right;
                Right = Right.Next;
            }
            curr = curr.Next;
        }
        curr.Next = (Left == null) ? Right : Left;

        return mHead.Next;
    }

    public static LinkedListNode<T> GetMiddle<T>(LinkedListNode<T> Head) where T : IComparable<T>
    {
        if (Head == null)
        {
            return Head;
        }

        LinkedListNode<T> slow, fast;
        slow = fast = Head;
        while (fast.Next != null && fast.Next.Next != null)
        {
            slow = slow.Next; fast = fast.Next.Next;
        }
        return slow;
    }

}





Aucun commentaire:

Enregistrer un commentaire