Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

c# - Why does short-circuiting not prevent MissingMethodException related to unreachable branch of logical AND (&&)?

While performing a check if there's a camera present and enabled on my windows mobile unit I encountered something I don't understand.

The code looks like this:

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

When I call CameraPresent2() it return false (there is no camera present). But when I call CameraPresent1() i recieve a MissingMethodException with comment "Could not find method: get_CameraEnabled Microsoft.WindowsMobile.Status.SystemState."

Is the second term evaluated in CameraPresent1 just because they both are property (at language level)?

Is there anything else that explains the difference in behaviour?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The second term is not evaluated.

The first term is not evaluated.

The CameraPresent1() method does not even start to execute.

When you call CameraPresent1() for the first time, the runtime must JIT-compile the MSIL into native code. This requires resolving all method calls, even ones that might be reached only conditionally. Compilation fails with the MissingMethodException.

With CameraPresent2(), the call to the getter of CameraEnabled is only compiled when CameraE() is called for the first time, which never happens.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...