为什么短路不能阻止与逻辑AND(&&)的不可达分支相关的MissingMethodException?

nj.*_*nj. 20 c# compact-framework short-circuiting

在检查我的Windows移动设备上是否有摄像头并启用时,我遇到了一些我不理解的东西.

代码如下所示:

    public static bool CameraP(){

        return Microsoft.WindowsMobile.Status.SystemState.CameraPresent;
    }

    public static bool CameraE()
    {
        return Microsoft.WindowsMobile.Status.SystemState.CameraEnabled;
    }

    public static bool CameraPresent1()
    {
        return Microsoft.WindowsMobile.Status.SystemState.CameraPresent
              && Microsoft.WindowsMobile.Status.SystemState.CameraEnabled;
    }

    public static bool CameraPresent2()
    {
        return CameraP() && CameraE();
    }
Run Code Online (Sandbox Code Playgroud)

当我调用CameraPresent2()它时返回false(没有相机存在).但是,当我打电话给CameraPresent1()我收到一个MissingMethodException并注释"找不到方法:get_CameraEnabled Microsoft.WindowsMo​​bile.Status.SystemState."

第二个术语的评估CameraPresent1是因为它们都是属性(在语言层面)吗?

还有什么能解释行为上的差异吗?

Ben*_*igt 31

第二个术语未经评估.

第一个术语未经评估.

CameraPresent1()方法甚至没有开始执行.

当您CameraPresent1()第一次调用时,运行时必须将MSIL JIT编译为本机代码.这需要解析所有方法调用,即使是只能有条件地访问的方法调用.编译失败了MissingMethodException.

对于CameraPresent2()getter的调用CameraEnabledCameraE()在第一次调用时编译,这种情况从未发生过.


Joh*_*zen 10

C#规范部分7.12

&&||运营商被称为条件逻辑运算符.它们也被称为"短路"逻辑运算符.

&&||运营商的&和条件版本| 运营商:

  • 该操作x && y对应于操作x & y,除非y仅在x不进行评估时进行评估false.

  • 该操作x || y对应于操作x | y,除非y仅在x不进行评估时进行评估true.


也就是说,C#规范保证当且仅当if为真时CameraE()才会被调用. CameraP()

这可能是积极的编译器优化的问题,因此实际程序似乎违反了语言规范...


编辑:

是否可以设置断点并显示反汇编窗口,以查看生成的确切代码?


Jus*_*gey 5

只是一个疯狂的猜测,但这可能是一个JIT编译问题?当调用CameraPresent1时,它是否尝试将调用Microsoft.WindowsMo​​bile.Status.SystemState.CameraEnabled映射到底层设备?由于找不到方法get_CameraEnabled,整个函数失败并出现MissingMethodException.