c# - 通用函数无法比较数组值和标准值

标签 c# generics

<分区>

本质上,我正在尝试为矩阵编写一个通用的暴力破解 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 指令,所以我不确定这里发生了什么。为什么这不起作用?

最佳答案

您必须使用 CompareTo() 而不是 > 操作。

参见此处:http://msdn.microsoft.com/en-gb/library/system.icomparable.aspx

在你的情况下你会把:

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

关于c# - 通用函数无法比较数组值和标准值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15096303/

相关文章:

c++ - IClassFactory::CreateInstance 方法的 pUnkOuter 参数

java - 嵌套泛型类型参数参数

c# - 从类型的部分名称获取 System.Type

c# - 在 C# 中获取字符串的 16 位哈希值

c# - Shell_NotifyIconA/Shell_NotifyIconW...有什么区别?

c# - 在网络浏览器控件中打印谷歌地图 - 不会显示方向线

java - Hibernate/JPA 中的类型安全主键

c# - 使用 Outlook API 获取特定文件夹

ios - 使用泛型和原始类型进行类型检查?

generics - Swift 泛型和相关类型的错误