简体   繁体   中英

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

Indexing an array, regardless of the dimensions, is a method call because it involves invoking the indexer operator .

Then why is the overload of the method System.Linq.Expressions.Expression.ArrayIndex that takes a single array index made to return a BinaryExpression whereas its other overloads , which represent indexing multi-dimensional arrays, are made to return MethodCallExpression s?

This just breaks the symmetry forcing me to remember this little anomaly. If they had made it a MethodCallExpression , I wouldn't have had to remember or keep note of anything.

I suspect it's because that's what it looks like in IL. The CLI has two different kinds of arrays: vectors which are "rank 1, 0 lower bound" arrays, and arrays which are "any rank, any lower bound" arrays. (Yes, the naming is very confusing. Sorry.)

Vectors are more efficient as the runtime can do simpler arithmetic to access them. IL has specific instructions for dealing with vectors, but general array access goes through a method.

To demonstrate this, compile this code:

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];
    }
}

Then look at it with ildasm - the last two lines of the method are compiled as:

// 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

So the expression tree is just representing the ldelem instruction as a binary operator (where the two operands are presumbly the array and the index) whereas it's using a method call for the multi-dimensional array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM