gpt4 book ai didi

c# - 不支持约束的通用方法

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:28 34 4
gpt4 key购买 nike

我正在尝试编写一个通用方法,它应该支持 ex int、double、float 等的内在类型。
该方法是对数组进行排序。
我收到一个编译时错误,说“无法将运算符 < 应用于类型 T”,这是我理解的,但我该如何解决呢?我应该使类通用并使用约束吗?
这是我的代码:

public static T[] Sort<T>(T[] inputArray) 
{
for (int i = 1; i < inputArray.Length; i++)
{
for (int j = i - 1; j >= 0; j--)
{
***if (inputArray[j + 1] < inputArray[j])***
{
T temp = inputArray[j + 1];
inputArray[j + 1] = inputArray[j];
inputArray[j] = temp;
}
else
{
break;
}
}
}
return inputArray;
}

最佳答案

C# 不支持对类型支持的运算符的通用约束。但是,.NET 提供了许多提供类似功能的接口(interface)。在这种情况下,您需要添加一个通用约束以确保 T实现 IComparable<T> .

public static T[] Sort<T>(T[] inputArray) where T : IComparable<T>
{
for (int i = 1; i < inputArray.Length; i++)
{
for (int j = i - 1; j >= 0; j--)
{
if (inputArray[j + 1].CompareTo(inputArray[j]) < 0)
{
T temp = inputArray[j + 1];
inputArray[j + 1] = inputArray[j];
inputArray[j] = temp;
}
else
{
break;
}
}
}
return inputArray;
}

关于c# - 不支持约束的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21610454/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com