c# - 如何在 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;
}
}
}
}
但现在我不能使用大于运算符,因为数组也可以是字符串数组。
解决方案
您可以添加一个约束:
public static void BubbleSort<T>(T[] arr)
where T : IComparable<T>
{
...
}
然后该CompareTo
方法将变为可用:
if (arr[j].CompareTo(arr[j + 1]) > 0)
推荐阅读
- vb.net - 释放文件锁
- php - ZF3 - 从助手那里获取 cookie
- java - 在 Lagom 中调用两个连续命令时出错
- cassandra - 无法在 Cassandra 中存储具有用户定义类型的 Scala 集
- sql - SQLite-根据新值更新旧值
- python - 从 Python 中的数学线性表达式中提取系数
- python - 如何更快地使用谷歌地图进行地理编码?
- java - 从 linux jdk 启动 jvisualvm 时出现乱码
- typescript - 在 TypeScript 中模拟通配符类型参数(具有不同的标识)
- python - 使用python将parquet文件分成3个parquet文件