gpt4 book ai didi

c# - Lambda 表达式编译

转载 作者:太空狗 更新时间:2023-10-29 21:37:06 25 4
gpt4 key购买 nike

给定下面的 lambda 表达式,其中 Province 类型包含一个公共(public)属性“byte CountryId”,Country 类型包含一个公共(public)属性“byte Id”。

Expression<Func<Province, bool>> exp = p => p.CountryId == country.Id;

表达式后来被 NHibernate Linq 提供程序使用并抛出异常。检查表达式变量exp时,我发现相等运算符的两边都被转换为Int32。

{p => (Convert(p.CountryId) = Convert(value
(AddressToGo.Business.Default.AddressComponents+<>c__DisplayClass0).country.Id))}

我不明白为什么两个字节值的相等运算符需要事先将这些值转换为 Int32。我直接写了表达式,没有让编译器为我做。以下表达式由 NHibernate Linq 提供程序转换得很好。

ParameterExpression prm = Expression.Parameter(typeof(Province), "p");
Expression<Func<Province, bool>> exp =
Expression.Lambda<Func<Province, bool>>
(
Expression.Equal
(
Expression.MakeMemberAccess(prm, typeof(Province).GetProperty("CountryId")),
Expression.Constant(country.Id, typeof(byte))
),
prm
);

所以,编译器输出类型转换后的表达式一定是有原因的。有什么想法吗?

最佳答案

这是符合规范的。引自 §4.1.5:

C# supports nine integral types: sbyte, byte, short, ushort, int, uint, long, ulong, and char. [...]

The integral-type unary and binary operators always operate with signed 32-bit precision, unsigned 32-bit precision, signed 64-bit precision, or unsigned 64-bit precision:

[...]

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.

因此,对于

byte b1;
byte b2;
bool b = (b1 == b2);

操作数 b1b2被提升为int之前 ==被调用。

关于c# - Lambda 表达式编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2072573/

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