[英]How to write overloaded generic extension methods for T[], T[][] without ambiguity?
我想編寫用於將向量和矩陣轉換為字符串的擴展方法。 我是用以下方式做到的。
對於矢量
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; }
}
對於Matrix
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的類型
你的方法沒有錯。 編譯器無法在它們之間進行選擇。
正如可以在該錯誤消息看到,編譯器可以假定T
是double[]
和匹配第一方法,或double
和匹配第二個。 這將通過明確提到您要使用的方法來解決:
Patterns.ToArray().GetString<double>();
編譯器無法判斷是否要調用GetString<double[]>
或GetString<double>
因為兩種方法都適合調用。
解決這個問題的最簡單方法是簡單地更改其中一個名稱(即GetArrayString<T>
)。 更好的解決方案IMO只有一種方法可以解決這兩種情況:
public static string Join<T>(this T[] sourceMatrix, string columnDelimiter = " ", string rowDelimiter = "\n")
{
if (sourceMatrix.Length == 0)
{
return string.Empty;
}
if (sourceMatrix[0] as Array == null)
{
return string.Join(columnDelimiter, sourceMatrix);
}
var rows = new List<string>();
foreach (T item in sourceMatrix)
{
var array = item as Array;
var row = "";
for (int j = 0; j < array.GetLength(0); j++)
row += array.GetValue(j) + columnDelimiter;
rows.Add(row);
}
return string.Join(rowDelimiter, rows);
}
用法:
int[] a = {1, 2, 3};
int[] b = { 1, 2, 4 };
int[][] c = {a, b};
Console.WriteLine(a.Join());
Console.WriteLine();
Console.WriteLine(c.Join());
輸出:
1 2 3
1 2 3
1 2 4
注意:這僅解決了1-2維,但可以很容易地推廣到n維。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.