C# 中的 Getter/Setter 问题

发布于 2024-07-16 02:01:34 字数 402 浏览 2 评论 0原文

我正在执行

static bool isWorking
    {
        get { return _isWorking; }
        set {
            myform.treeView1.Enabled = !value;
            _isWorking = value;
        }
    }

并单步执行调试器,显示它停止在第一组行处。 尝试此行后,

set { myform.treeView1.Enabled = !(_isWorking = value); }

我看到 isWorking 已设置,但 myform.treeView1.Enabled 未设置。 这是怎么回事?

I am doing

static bool isWorking
    {
        get { return _isWorking; }
        set {
            myform.treeView1.Enabled = !value;
            _isWorking = value;
        }
    }

and stepping through the debugger shows it stops at the first set line.
After trying this line instead

set { myform.treeView1.Enabled = !(_isWorking = value); }

I see that isWorking is set but myform.treeView1.Enabled is not. Whats going on?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

临风闻羌笛 2024-07-23 02:01:34

“调试器显示它停止”是什么意思? 是否可能 myform 为 null,或者 myform.treeView1 为 null?

我不记得这种情况下的确切评估顺序,但它可以解释您所描述的症状。 不过,了解调试器“停止”的原因至关重要。 另一种可能性是您尝试从非 UI 线程访问 UI,这会阻止对 Enabled 的分配正常工作。

哦,请不要使用你的第二个版本 - 分配作为副作用是非常非常罕见的好主意。 我知道的唯一惯用用法是使用 IO: 循环时,

string line;
while ( (line = reader.ReadLine()) != null)

我认为这是可以接受的,因为它相当常见。 在这种情况下,看起来您确实可以表示“==”而不是“=”。

What do you mean by "the debugger shows it stops"? Is it possibly that myform is null, or myform.treeView1 is null?

I can't remember the exact evaluation order in this case, but it could explain the symptoms you're describing. Knowing why the debugger "stops" is crucial though. Another possibility is that you're trying to access the UI from a non-UI thread, which would prevent the assignment to Enabled from working properly.

Oh, and please don't use your second version - assignment as a side-effect is very, very rarely a good idea. The only idiomatic use I know is when looping with IO:

string line;
while ( (line = reader.ReadLine()) != null)

and I only consider that acceptable because it's reasonably common. In this case it really looks like you could mean "==" instead of "=".

淡忘如思 2024-07-23 02:01:34

因为 (_isWorking = value) 始终返回 true。 如果你会写:

myform.treeView1.Enabled = !(_isWorking == value);

它的工作原理如下:如果 isWorking 等于 value 那么禁用 treeView。 但就你而言 - 不

Because (_isWorking = value) returns always true. If you would write:

myform.treeView1.Enabled = !(_isWorking == value);

It works like: if isWorking is equal to value then Disable treeView. But in you case - no

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文