我想编写将向量和矩阵转换为字符串的扩展方法。我通过以下方式做到了这一点。
对于向量
public static string GetString<T>(this T[] SourceMatrix, string ColumnDelimiter = " ")
{
try
{
string result = "";
for (int i = 0; i < SourceMatrix.GetLength(0); i++)
result += SourceMatrix[i] + ColumnDelimiter;
return result;
}
catch (Exception ee) { return null; }
}
对于矩阵
public static string GetString<T>(this T[][] SourceMatrix, string ColumnDelimiter = " ", string RowDelimiter = "\n")
{
try
{
string result = "";
for (int i = 0; i < SourceMatrix.GetLength(0); i++)
{
for (int j = 0; j < SourceMatrix[i].GetLength(0); j++)
result += SourceMatrix[i][j] + "" + ColumnDelimiter;
result += "" + RowDelimiter;
}
return result;
}
catch (Exception ee) { return null; }
}
现在我正在使用以下导致歧义的代码。
List<double[]> Patterns= GetPatterns();
Patterns.ToArray().GetString();
错误
Error 5 The call is ambiguous between the following methods or properties:
'MatrixMathLib.MatrixMath.GetString<double[]>(double[][], string)' and
'MatrixMathLib.MatrixMath.GetString<double>(double[][], string, string)'
谁能建议我正确编写这些扩展方法。
提前致谢。
最佳答案
你的方法没有问题。编译器无法在它们之间进行选择。
如您在错误消息中所见,编译器可能假定 T
为 double[]
并匹配第一个方法,或 double
并匹配第二个。这将通过明确提及您要使用的方法来解决:
Patterns.ToArray().GetString<double>();
关于c# - 如何为 T[]、T[][] 编写重载的泛型扩展方法而不会产生歧义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25102991/