通用函数无法在数组值和标准值之间进行比较

时间:2013-02-26 18:15:21

标签: c# generics

基本上,我正在尝试为矩阵编写通用的bruteforce getMax()方法。这就是我所拥有的:

 private T getMax <T>(T[,] matrix, uint rows, uint cols) where T : IComparable<T>
    {
        T max_val = matrix[0, 0];
        for (int row = 0; row < rows; ++row)
        {
            for (int col = 0; col < cols; ++col)
            {
                if (matrix[row, col] > max_val)
                {
                    max_val = matrix[row, col];
                }
            }
        }
        return max_val;
    }

这将无法编译,错误为Operator '>' cannot be applied to operands of type 'T' and 'T'。我给出了IComparable指令,所以我不确定这里发生了什么。为什么这不起作用?

3 个答案:

答案 0 :(得分:7)

您必须使用CompareTo()而不是&gt;操作

见这里:http://msdn.microsoft.com/en-gb/library/system.icomparable.aspx

在你的情况下,你会把:

if (matrix[row, col].CompareTo(max_val) > 0)

答案 1 :(得分:2)

实施IComparable意味着它定义了CompareTo方法,而不是定义了>运算符。你需要使用:

if (matrix[row, col].CompareTo(max_val) > 0) {

答案 2 :(得分:1)

if (matrix[row, col] > max_val)

应该是

if (matrix[row, col].CompareTo(max_val) > 0)

由于IComparable仅提供CompareTo而非>

相关问题