Expression trees - unnecessary conversion to int32

后端 未结 2 1115
一个人的身影
一个人的身影 2021-02-19 10:41

Expression trees seem to build an unnecessary conversion when working with bytes and shorts, they convert both sides (in binary expressions for instance) to int32.

This

2条回答
  •  醉酒成梦
    2021-02-19 11:08

    To answer your question:

    Why Expression trees seem to build an unnecessary conversion when working with bytes and shorts... So the question is, what is the reason for this behavior?

    The answer is hidden in the fact, that C# types short, ushort, byte and sbyte lack the arithmetic, comparison... operators:

    Extract: 4.1.5 Integral types

    For the binary +, –, *, /, %, &, ^, |, ==, !=, >, <, >=, and <= operators, the operands are converted to type T, where T is the first of int, uint, long, and ulong that can fully represent all possible values of both operands. The operation is then performed using the precision of type T, and the type of the result is T (or bool for the relational operators). It is not permitted for one operand to be of type long and the other to be of type ulong with the binary operators.

    The 7.9.1 Integer comparison operators describes available operators and their operands

    bool operator ==(int x, int y);
    bool operator ==(uint x, uint y);
    bool operator ==(long x, long y);
    bool operator ==(ulong x, ulong y);
    ... // other operators, only for int, uint, long, ulong
    

    The conversion is done for you by Compiler (the reason why you succeed to build that without explicit conversion)

    Because there are no operators working with short... the conversion must be applied. And of course, it later depends on the LINQ provider, how to convert such "expression" into SQL.

提交回复
热议问题