条件为false,但if语句中的代码已执行 [英] Condition false, but code inside the if statement executed

查看:943
本文介绍了条件为false,但if语句中的代码已执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法:

public bool ConnectAsync()
{
    if (IsConnected)
        throw new InvalidOperationException("Socket is already connected");

    if (IsConnecting)
    {
        throw new InvalidOperationException("Attempt to connect in progress");
    }

    . . .
}

其中:

    private readonly object padLock = new object();

    private bool isConnecting = false;

    public bool IsConnected
    {
        get
        {
            lock (padLock)
            { return socket.Connected; }
        }
    }

    public bool IsConnecting
    {
        get
        {
            lock (padLock)
            { return isConnecting; }
        }

        private set
        {
            lock (padLock)
            { isConnecting = value; }
        }
    }

如果我的变量isConnecting为false,为什么会执行if语句中的代码?

Why the code inside the if statement is executed if my variable isConnecting is false?

编辑

如果我使用提交的 isConnecting 而不是属性 IsConnecting 我有相同的行为。代码在任何地方都在同一个线程中运行。

Edit:
If I use the filed isConnecting instead of the property IsConnecting I have the same behavior. The code runs in the same thread anywhere.

编辑2

最后这是有效的:

lock (padLock)
{
    if (IsConnecting)
        throw new InvalidOperationException("Attempt to connect in progress");
}

这样做有效:

{
    if (IsConnecting)
        throw new InvalidOperationException("Attempt to connect in progress");
}

但为什么?

推荐答案

调试器中的Expression窗口是触发异常的窗口,而不是代码。删除表达式(或观察),它应该按预期工作。

The Expression window you have in the debugger is the one triggering the exception, not your code. Remove expressions (or watch) and it should work as expected.

这篇关于条件为false,但if语句中的代码已执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆