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

标签 c# generics extension-methods default-parameters

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

对于向量

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/

相关文章:

c# - 关于ServiceStack.Redis的一些问题

c# - 在c#中获取字符串的第二个单词

c# - 使用通用类型拆分字符串扩展?

iOS - FileManager 扩展的最佳实践

c# - 为什么有人说 "Builder Pattern"比使用 Fluent 接口(interface)的扩展方法更好?

C# web 和 ftp 爬虫库

c# - 如何将 CTRL + SHIFT + V 指定为按键手势?

Swift 2 通用数据结构不符合 Equatable 协议(protocol)

c# - 如何在 C# 中获取字典值集合的计数

java - 使用 java 泛型和接口(interface)扩展可比对象