【问题标题】:Why does the compiler convert bool to integer and back to bool instead of returning the bool itself?为什么编译器将 bool 转换为整数并返回 bool 而不是返回 bool 本身?
【发布时间】:2016-10-23 19:05:45
【问题描述】:

我正在通过 ILSPY 阅读 AForge.Video.FFMPEG 程序集中的 VideoFileWriter 类(我很想看看特定方法是如何工作的)并发现了这个:

public bool IsOpen {
    [return: MarshalAs(UnmanagedType.U1)]
    get {
        return ((this.data != null) ? 1 : 0) != 0;
    }
}

将 bool 转换为整数而不是返回 bool 转换的原因是什么,而不是只做 this.data != null

【问题讨论】:

  • 尝试与 JustDecompile 比较
  • 或者试试 DotPeek

标签: c# ffmpeg aforge


【解决方案1】:

是反编译的代码,很可能只是反编译器的小故障。


经过一番思考,这是一个合理的实现,可能会变成相同的编译代码

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;
    }
}

【讨论】:

  • 有道理。我尝试了其他反编译器并得到了不同的输出,例如 `public bool IsOpen { get { object obj; if (this.data != null) { obj = 1; } 其他 { obj = null; } 返回(字节)obj; } }`
猜你喜欢
  • 2010-09-20
  • 2019-06-29
  • 1970-01-01
  • 2018-05-27
  • 2012-08-24
  • 2014-07-01
  • 2012-01-14
相关资源
最近更新 更多