简体   繁体   English

为什么将一维数组索引为BinaryExpression而不是MethodCallExpression的实例?

[英]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? 那么为什么System.Linq.Expressions.Expression.ArrayIndex方法的重载使得单个数组索引返回BinaryExpressionother overloads (表示索引多维数组)会返回MethodCallExpression

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. 如果他们将其设为MethodCallExpression ,我就不必记住或记下任何事情。

I suspect it's because that's what it looks like in IL. 我怀疑是因为这就是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. CLI有两种不同的数组: 向量是“秩1,0下限”数组, 数组是“任何等级,任何下限”数组。 (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. IL具有处理向量的具体指令,但是一般的数组访问通过一种方法。

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: 然后用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

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. 因此表达式树只是将ldelem指令表示为二元运算符(其中两个操作数是数组和索引),而它使用多维数组的方法调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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