表达式树在处理字节和短路时似乎构建了一个不必要的转换,它们将两边(例如二进制表达式)转换为int32。
这是我见过的一些Linq提供程序中的一个问题,每个提供程序都必须剥离这个冗余层才能获得原始表达式。(NHibernate没有删除这一层,并在SQL查询中创建了一个糟糕的CAST)。
// 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));
如果您尝试构建一个进行精确比较的表达式(不进行转换),那么您将成功。
所以问题是,这种行为的原因是什么?
编辑.net 4.0 64位,同样适用于4.5 64位
回答您的问题:
为什么表达式树在处理字节和short时似乎构建了不必要的转换。。。所以问题是,这种行为的原因是什么?
答案隐藏在以下事实中:C#类型short
、ushort
、byte
和sbyte
缺乏算术、比较。。。运算符:
摘录:4.1.5整体式
对于二进制+,–,*,/,%,&,^,|,==,!=,><,>=,并且<运算符,操作数转换为类型
T
,其中T
是第一个int
、uint
、long
和ulong
的两个操作数的值。然后使用类型为T
的精度,并且结果的类型是T
(或关系运算符)。不允许一个操作数为类型long,另一个类型ulong,带有二进制运算符。
7.9.1整数比较运算符描述了可用的运算符及其操作数
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
转换是由编译器为您完成的(这就是您在没有显式转换的情况下成功构建它的原因)
因为没有操作人员处理短。。。必须应用转换。当然,它稍后取决于LINQ提供者,如何将这样的"表达式"转换为SQL。
这真的很有趣;不幸的是,表达式树编译器的规则并没有被正式指定——规范中有一个简短的"在其他地方",但是:它们并不是真正的。
如果它造成了问题,你可以尝试发现并删除它——如下所示,它是100%未经测试的,使用风险自负,等等:
static void Main()
{
Console.WriteLine(((Expression<Func<short, short, bool>>)((s, s1) => s == s1)).Unmunge());
Console.WriteLine(((Expression<Func<byte, byte, bool>>)((s, s1) => s == s1)).Unmunge());
}
static Expression<T> Unmunge<T>(this Expression<T> expression)
{
return (Expression<T>)RedundantConversionVisitor.Default.Visit(expression);
}
class RedundantConversionVisitor : ExpressionVisitor
{
private RedundantConversionVisitor() { }
public static readonly RedundantConversionVisitor Default = new RedundantConversionVisitor();
protected override Expression VisitBinary(BinaryExpression node)
{
if(node.Type == typeof(bool) && node.Method == null
&& node.Left.NodeType == ExpressionType.Convert && node.Right.NodeType == ExpressionType.Convert
&& node.Left.Type == node.Right.Type)
{
UnaryExpression lhs = (UnaryExpression)node.Left, rhs = (UnaryExpression)node.Right;
if (lhs.Method == null && rhs.Method == null && lhs.Operand.Type == rhs.Operand.Type)
{
// work directly on the inner values
return Expression.MakeBinary(node.NodeType, lhs.Operand, rhs.Operand, node.IsLiftedToNull, node.Method);
}
}
return base.VisitBinary(node);
}
}
输出之前:
(s, s1) => (Convert(s) == Convert(s1))
(s, s1) => (Convert(s) == Convert(s1))
输出后:
(s, s1) => (s == s1)
(s, s1) => (s == s1)