[英]How to test if an object is an array of arrays/jagged array
我正在嘗試測試對象是哪種數組:1D,2D或數組/鋸齒狀數組。
這是我嘗試過的:
if (o is Array && ((Array)o).Rank == 2) {
Console.Write ("2D-Array: ");
}
/* else if (o[0] is Array) {
Console.WriteLine ("Jagged Array: ");
} */
else if (o is Array) {
Console.Write ("1D-Array: ");
}
但是中間測試無法正常工作,因為Cannot apply indexing with [] to an expression of type 'object'
你還能怎么做? 提前致謝。
由於o
是一個object
並且您沒有將其裝箱為數組,因此該代碼無法編譯。 這是一種更簡單的方法:
var arr = o as Array;
if(arr != null)
{
if(arr.Rank == 2)
{
Console.Write ("2D-Array: ");
}
else if (arr.Length > 0 && arr.GetValue(0) is Array)
{
Console.WriteLine ("Jagged Array: ");
}
else
{
Console.Write ("1D-Array: ");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.