C# 中的 Getter/Setter 问题
我正在执行
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“调试器显示它停止”是什么意思? 是否可能
myform
为 null,或者myform.treeView1
为 null?我不记得这种情况下的确切评估顺序,但它可以解释您所描述的症状。 不过,了解调试器“停止”的原因至关重要。 另一种可能性是您尝试从非 UI 线程访问 UI,这会阻止对
Enabled
的分配正常工作。哦,请不要使用你的第二个版本 - 分配作为副作用是非常非常罕见的好主意。 我知道的唯一惯用用法是使用 IO: 循环时,
我认为这是可以接受的,因为它相当常见。 在这种情况下,看起来您确实可以表示“==”而不是“=”。
What do you mean by "the debugger shows it stops"? Is it possibly that
myform
is null, ormyform.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:
and I only consider that acceptable because it's reasonably common. In this case it really looks like you could mean "==" instead of "=".
因为 (_isWorking = value) 始终返回 true。 如果你会写:
它的工作原理如下:如果 isWorking 等于 value 那么禁用 treeView。 但就你而言 - 不
Because (_isWorking = value) returns always true. If you would write:
It works like: if isWorking is equal to value then Disable treeView. But in you case - no