表达式树-不必要转换为int32 [英] Expression trees - unnecessary conversion to int32
问题描述
表达式树在处理字节和短裤时似乎会建立不必要的转换,它们会将双方(例如,在二进制表达式中)都转换为int32.
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.
这是我看到的某些Linq提供程序中的一个问题,每个提供程序都必须剥离此冗余层才能获得原始表达. (NHibernate不会删除该层,而是在SQL查询中创建了一个糟糕的CAST.)
This is an issue in some Linq providers that I've seen, each has to peel this redundant layer to get to the original expression. (NHibernate doesn't remove this layer and creates an awful CAST in the SQL query).
// no conversion
Console.WriteLine((Expression<Func<int, int, bool>>) ((s, s1) => s == s1));
// converts to int32
Console.WriteLine((Expression<Func<short, short, bool>>) ((s, s1) => s == s1));
// converts to int32
Console.WriteLine((Expression<Func<byte, byte, bool>>) ((s, s1) => s == s1));
如果您尝试构建一个进行此精确比较(不进行转换)的表达式,那么您会成功.
If you try to build an expression that makes this exact comparison (without the conversion), you'll succeed.
问题是,这种行为的原因是什么?
So the question is, what is the reason for this behavior?
编辑 .net 4.0 64bit,同样适用于4.5 64bit
EDIT .net 4.0 64bit, the same applies to 4.5 64bit
推荐答案
回答您的问题:
为什么在处理字节和短裤时,表达式树似乎建立了不必要的转换... 所以问题是,这种行为的原因是什么?
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?
答案隐藏在以下事实中: C#类型short
,ushort
,byte
和sbyte
缺乏算术,比较...运算符:
The answer is hidden in the fact, that C# types short
, ushort
, byte
and sbyte
lack the arithmetic, comparison... operators:
摘录: 4.1.5整数类型
对于二进制+,–,*,/,%,&,^,|,==,!=,>,<,> =和< = 运算符,操作数将转换为类型
T
,其中T
是第一个 可以完全代表所有可能的int
,uint
,long
和ulong
两个操作数的值.然后使用 类型为T
的精度,结果的类型为T
(或对于 关系运算符).不允许一个操作数为 类型为long,另一个类型为ulong并带有二进制运算符.
For the binary +, –, *, /, %, &, ^, |, ==, !=, >, <, >=, and <= operators, the operands are converted to type
T
, whereT
is the first ofint
,uint
,long
, andulong
that can fully represent all possible values of both operands. The operation is then performed using the precision of typeT
, and the type of the result isT
(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.
7.9.1整数比较运算符描述可用的运算符及其操作数
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
编译器为您完成了转换(无需显式转换就可以成功构建它的原因)
因为没有运算符正在使用short,所以必须应用转换.当然,稍后它取决于LINQ提供程序,如何将这种表达式"转换为SQL.
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.
这篇关于表达式树-不必要转换为int32的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!