gpt4 book ai didi

c# - 如何为 T[]、T[][] 编写重载的泛型扩展方法而不会产生歧义?

转载 作者:太空狗 更新时间:2023-10-29 22:37:12 35 4
gpt4 key购买 nike

我想编写将向量和矩阵转换为字符串的扩展方法。我通过以下方式做到了这一点。

对于向量

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)'

谁能建议我正确编写这些扩展方法。

提前致谢。

最佳答案

你的方法没有问题。编译器无法在它们之间进行选择。

如您在错误消息中所见,编译器可能假定 Tdouble[] 并匹配第一个方法,或 double 并匹配第二个。这将通过明确提及您要使用的方法来解决:

Patterns.ToArray().GetString<double>();

关于c# - 如何为 T[]、T[][] 编写重载的泛型扩展方法而不会产生歧义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25102991/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com