gpt4 book ai didi

c# - c# 表达式上的奇怪类型转换

转载 作者:行者123 更新时间:2023-12-04 12:31:14 25 4
gpt4 key购买 nike

让我们有一个简单的类

class User
{
public byte IdByte { get; set; }
}

所以当我写这样的表达式时:


Expression<Func<User, bool>> expression1 = x => x.IdByte == 3;

Expression<Func<User, bool>> expression2 = x => x.IdByte == (byte)3;

byte b = 3;
Expression<Func<User, bool>> expression3 = x => x.IdByte == b;

Expression<Func<User, bool>> expression4 = x => x.IdByte == byte.MaxValue;

然后观察表达式调试 View ,我看到有一个额外的类型转换类型 System.Int32 :

//expression1  ------>  x => (Convert(x.IdByte, Int32) == 3)
//expression2 ------> x => (Convert(x.IdByte, Int32) == 3)
//expression3 ------> x => (Convert(x.IdByte, Int32) == Convert(value(....c__DisplayClass1_0).b, Int32))
//expression4 ------> x => (Convert(x.IdByte, Int32) == 255)

在第一个和第二个表达式中,将右侧 - 3 转换为 byte 比将左侧转换为 int 更合理。
在其余情况下,左侧和右侧是字节
我的问题是为什么应用这些转换?

最佳答案

让我们检查一下 the spec :

Integer comparison operators

The predefined integer comparison operators are:

bool operator ==(int x, int y);
bool operator ==(uint x, uint y);
bool operator ==(long x, long y);
bool operator ==(ulong x, ulong y);

bool operator !=(int x, int y);
bool operator !=(uint x, uint y);
bool operator !=(long x, long y);
bool operator !=(ulong x, ulong y);

bool operator <(int x, int y);
bool operator <(uint x, uint y);
bool operator <(long x, long y);
bool operator <(ulong x, ulong y);

bool operator >(int x, int y);
bool operator >(uint x, uint y);
bool operator >(long x, long y);
bool operator >(ulong x, ulong y);

bool operator <=(int x, int y);
bool operator <=(uint x, uint y);
bool operator <=(long x, long y);
bool operator <=(ulong x, ulong y);

bool operator >=(int x, int y);
bool operator >=(uint x, uint y);
bool operator >=(long x, long y);
bool operator >=(ulong x, ulong y);

Each of these operators compares the numeric values of the two integer operands and returns a bool value that indicates whether the particular relation is true or false.

如您所见,我们实际上并没有比较两个 bytes 或两个 sbytes== 运算符,charsshortsushorts

但是,从这些类型到 int 存在隐式转换,因此编译器将这些转换应用于双方,并使用 bool ==(int x, int y).

如果你写:

byte val = 3;
bool b = val == (byte)4;

编译器会有效地将其转换为:

byte val = 3;
bool b = (int)val == (int)(byte)4;

(int)(byte)4 转换当然是完全没有必要的:编译器只会将其转换为整数文字。

byte val = 3;
bool b = (int)val == 4;

关于c# - c# 表达式上的奇怪类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68921540/

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