[英]Initialize and return jagged array in one line
目前我正在這樣做
public int[][] SomeMethod()
{
if (SomeCondition)
{
var result = new int[0][];
result[0] = new int[0];
return result;
}
// Other code,
}
現在,我只想返回[0] [0]的空鋸齒數組。 是否可以將三行減少為一行。 我想實現這樣的目標
public int[][] SomeMethod()
{
if (SomeCondition)
{
return new int[0][0];
}
// Other code,
}
可能嗎?
通常,您可以讓編譯器為您計算元素:
public int[][] JaggedInts()
{
return new int[][] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 7, 8, 9, 10 } };
}
或者,如果您希望它非常緊湊,請使用表達式主體:
public int[][] JaggedInts() => new int[][] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 7, 8, 9, 10 } };
由於您要求一個空的鋸齒狀數組,因此您已經有了它:
var result = new int[0][];
問題的下一行將引發運行時異常,因為[0]是數組中的第一個元素,長度必須為1個或多個元素;
result[0] = new int[0]; // thows IndexOutOfRangeException: Index was outside the bounds of the array.
這是我想您只要求一行的內容:
public int[][] Empty() => new int[0][];
試試這個示例頁面。 希望對您有所幫助
通過返回鋸齒形數組的值,可以得到一些模棱兩可的結果,如果您想返回鋸齒形數組的某些特定索引的特定值,則可以通過將其分配給變量來返回
public static int aaa()
{
int[][] a = new int[2][] { new int[] { 1, 2 }, new int[] { 3, 4 } };
int abbb=a[0][0];
Console.WriteLine(a[0][0]);
return abbb;
}
下面的代碼將返回1,因為這是鋸齒狀數組的第一個元素
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.