gpt4 book ai didi

c# - 表达式树 - 不必要的转换为 int32

转载 作者:可可西里 更新时间:2023-11-01 08:25:31 25 4
gpt4 key购买 nike

在处理字节和短裤时,表达式树似乎构建了一个不必要的转换,它们将两边(例如二进制表达式)转换为 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 64bit,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# 类型 shortushortbytesbyte 缺少算术、比较...运算符:

摘录: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.

7.9.1 Integer comparison operators描述可用的运算符及其操作数

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。

关于c# - 表达式树 - 不必要的转换为 int32,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18572788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com