尝试在 C# 中使用三元运算符时出错
这是我的代码:
public void ToggleCheckBox()
{
if (chkSelected.Checked) ? chkSelected.Checked = false : chkSelected.Checked = true;
//This works, but I want to write it using a ternary.
if (chkSelected.Checked)
{
chkSelected.Checked = false;
}
else
{
chkSelected.Checked = true;
}
}
我搞砸了什么?谢谢!
Here's my code:
public void ToggleCheckBox()
{
if (chkSelected.Checked) ? chkSelected.Checked = false : chkSelected.Checked = true;
//This works, but I want to write it using a ternary.
if (chkSelected.Checked)
{
chkSelected.Checked = false;
}
else
{
chkSelected.Checked = true;
}
}
What did I mess up on? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
要么执行此操作:
...或执行此操作:
或放弃检查并执行此操作:
Either do this:
...or this:
Or abandon the check and do this:
将其写为
。
要重写您的确切示例,它会变得像这样混乱:
在本例中,
?:
运算符返回true
或false
。它无法执行分配。Write this as
instead.
To rewrite your exact example, it get's messy like this:
The
?:
operator returns, in this case, eithertrue
orfalse
. It cannot perform assignment.您使用的是赋值而不是比较,并且那里不需要
if
。事实上,目前还不清楚您的意图是什么,但我猜是:You're using assignment instead of comparison, and you don't need an
if
there. In fact, it isn't too clear what your intent is, but I'd guess it is:为什么不这样做:
另外,它无法编译,因为您在它前面放置了
if
。删除它,它也会起作用!Why not do:
Also, it does not compile, because of the
if
you put in front of it. Remove that and it will work as well!我认为你的意思是:
可以缩短为:
I think you mean:
which can be shortened to:
因为你必须像赋值一样使用:
三元运算符就像赋值一样使用
并不是一个好主意..
但是在这里这样做并做更短的方式
Because you have to use like a assignation:
Ternary operator is used like a assignation
But here It is not really a good idea to do that here and do
Shorter way..