簡體   English   中英

為什么將一維數組索引為BinaryExpression而不是MethodCallExpression的實例?

[英]Why is an instance of indexing a one-dimensional array a BinaryExpression and not a MethodCallExpression?

索引數組(無論維度如何)都是方法調用,因為它涉及調用索引器運算符

那么為什么System.Linq.Expressions.Expression.ArrayIndex方法的重載使得單個數組索引返回BinaryExpressionother overloads (表示索引多維數組)會返回MethodCallExpression

這只是打破了對稱性,迫使我記住這個小異常。 如果他們將其設為MethodCallExpression ,我就不必記住或記下任何事情。

我懷疑是因為這就是IL的樣子。 CLI有兩種不同的數組: 向量是“秩1,0下限”數組, 數組是“任何等級,任何下限”數組。 (是的,命名很混亂。抱歉。)

向量更有效,因為運行時可以更簡單的算術來訪問它們。 IL具有處理向量的具體指令,但是一般的數組訪問通過一種方法。

為了演示這一點,請編譯以下代碼:

class Test
{
    static void Main()
    {
        int[] vector = new int[10];
        int[,] array = new int[10, 10];
        int x = vector[0];
        int y = array[0, 0];
    }
}

然后用ildasm查看它 - 該方法的最后兩行編譯為:

// int x = vector[0]
IL_0013:  ldloc.0
IL_0014:  ldc.i4.0
IL_0015:  ldelem.i4
IL_0016:  stloc.2

// int y = array[0, 0]
IL_0017:  ldloc.1
IL_0018:  ldc.i4.0
IL_0019:  ldc.i4.0
IL_001a:  call       instance int32 int32[0...,0...]::Get(int32,
                                                          int32)
IL_001f:  stloc.3

因此表達式樹只是將ldelem指令表示為二元運算符(其中兩個操作數是數組和索引),而它使用多維數組的方法調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM