本質上,我試圖爲矩陣編寫通用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指令,所以我不確定這裏發生了什麼。爲什麼這不起作用?
與其將行和列傳遞給方法,您可以使用'GetLength'來查找維度,除非您特別想要搜索矩陣的子集。 – Servy 2013-02-26 18:21:44