不同的数组类型作为方法的参数

Sta*_*mov 1 c# sorting methods selection

我有个问题.我想实现一个插入排序,但在不同类型的数组 - int,string和double,但我不知道如何在方法中获得不同类型的参数.这是一些代码:

private static string InsertionSort(int[] array)
    {

        Stopwatch stopwatch = new Stopwatch();
        int index, i, j;
        stopwatch.Start();
        for (i = 1; i < array.Length; i++)
        {
            index = array[i];
            j = i;
            while ((j > 0) && (array[j - 1] > index))
            {
                array[j] = array[j - 1];
                j = j - 1;
            }
            array[j] = index;
        }
        stopwatch.Stop();
        return stopwatch.Elapsed.ToString(); 
    }
Run Code Online (Sandbox Code Playgroud)

我尝试使用InsertionSort(dynamic []数组)但它仍然不起作用.

Ned*_*nov 6

你可以使用其他人提到的泛型,但是能够比较你需要添加类型实现的约束的项目IComparable.您还需要更改要使用的代码CompareTo而不是>操作员.

private static string InsertionSort<T>(T[] array) where T : IComparable<T>
{
    Stopwatch stopwatch = new Stopwatch();
    int i, j;
    T index;
    stopwatch.Start();
    for (i = 1; i < array.Length; i++)
    {
    index = array[i];
    j = i;
    while ((j > 0) && (array[j - 1].CompareTo(index) > 0))
    {
        array[j] = array[j - 1];
        j = j - 1;
    }
    array[j] = index;
    }
    stopwatch.Stop();
    return stopwatch.Elapsed.ToString(); 
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你想要通用,也可以一直使用`IComparable <T>`.这将避免在对CompareTo调用值时使用值类型. (2认同)