本质上,我正在尝试为矩阵编写通用的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;
}
Run Code Online (Sandbox Code Playgroud)
这将无法编译,错误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)
Run Code Online (Sandbox Code Playgroud)