为什么编译器将 bool 转换为整数并返回 bool 而不是返回 bool 本身?
Why does the compiler convert bool to integer and back to bool instead of returning the bool itself?
我正在通过 ILSPY 从 AForge.Video.FFMPEG
汇编中读取 VideoFileWriter
class(我有兴趣了解特定方法的工作原理)并发现了这个:
public bool IsOpen {
[return: MarshalAs(UnmanagedType.U1)]
get {
return ((this.data != null) ? 1 : 0) != 0;
}
}
为什么要将 bool 转换为整数而不是返回 bool 而只是 this.data != null
?
这是反编译代码,可能只是反编译器的一个小故障。
经过一番思考,这里有一个合理的实现,可能会变成相同的编译代码
public enum ConnectionState
{
Closed = 0,
Open = 1,
Opening = 2,
OtherStuff = 3,
AndSoOn = 4,
}
public bool IsOpen
{
get
{
ConnectionState state;
if (this.data != null)
{
state = ConnectionState.Open;
}
else
{
state = ConnectionState.Closed;
}
return state != ConnectionState.Closed;
}
}
我正在通过 ILSPY 从 AForge.Video.FFMPEG
汇编中读取 VideoFileWriter
class(我有兴趣了解特定方法的工作原理)并发现了这个:
public bool IsOpen {
[return: MarshalAs(UnmanagedType.U1)]
get {
return ((this.data != null) ? 1 : 0) != 0;
}
}
为什么要将 bool 转换为整数而不是返回 bool 而只是 this.data != null
?
这是反编译代码,可能只是反编译器的一个小故障。
经过一番思考,这里有一个合理的实现,可能会变成相同的编译代码
public enum ConnectionState
{
Closed = 0,
Open = 1,
Opening = 2,
OtherStuff = 3,
AndSoOn = 4,
}
public bool IsOpen
{
get
{
ConnectionState state;
if (this.data != null)
{
state = ConnectionState.Open;
}
else
{
state = ConnectionState.Closed;
}
return state != ConnectionState.Closed;
}
}