首页 > 解决方案 > 如何在 C# 中将数组作为未知类型的参数传递?

问题描述

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

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

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

标签: c#arrayssorting

解决方案


您可以添加一个约束:

public static void BubbleSort<T>(T[] arr)
    where T : IComparable<T>
{
   ...
}

然后该CompareTo方法将变为可用:

if (arr[j].CompareTo(arr[j + 1]) > 0)

推荐阅读