如何在C#中将数组作为未知类型的参数传递?

N.K*_*sch 1 c# arrays sorting

我想对整数或双精度数组进行排序.为此,我想使用一种方法.我的问题是我不知道如何传递一个未知类型的数组作为参数.我试过这个

public static void BubbleSort<T>(T[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            for (int j = 0; j < arr.Length - 1; j++)
            {
                //Can't use greater than because of T
                if (arr[j] > arr[j + 1])
                {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是现在我不能使用大于运算符,因为数组也可以是字符串数组.

C.E*_*uis 7

您可以添加约束:

public static void BubbleSort<T>(T[] arr)
    where T : IComparable<T>
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

然后该CompareTo方法将可用:

if (arr[j].CompareTo(arr[j + 1]) > 0)
Run Code Online (Sandbox Code Playgroud)