作者VVll (J.)
看板C_Sharp
标题Re: [问题] ?: 运算子的问题
时间Mon Jan 5 17:53:21 2015
※ 引述《apologize (人生在世很惬意)》之铭言:
: checkBox1.Checked == true ? timer1.Enabled = true : timer1.Enabled = false;
: 我是这样写,可是他说只能用陈述式表示,
: 可是不是要判别式才能用?请问要怎样修改?
MSDN ?: 运算子 (C# 参考)
http://msdn.microsoft.com/zh-tw/library/ty67wk28.aspx
语法
condition ? first_expression : second_expression;
因为expression 实际上是回传给这个语法的值
e.g
int a = (true ? 0 : 1);//合法
int b = (false ? "0" : "1");//非法,因为b是int,但expression是string
所以你的程式应该写成
timer1.Enabled = (checkBox1.Checked ? true : false);
或者
if(checkBox1.Checked)
{
timer1.Enabled = true;
}
else
{
timer1.Enabled = false;
}
若这样写也可以正常赋值,但无意义
bool tmp = checkBox1.Checked ? timer1.Enabled = true : timer1.Enabled = false;
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 211.72.185.162
※ 文章网址: http://webptt.com/cn.aspx?n=bbs/C_Sharp/M.1420451609.A.809.html
※ 编辑: VVll (211.72.185.162), 01/05/2015 18:04:48
1F:→ AmosYang: 或着直接 timer1.Enabled = checkBox1.Checked ? :D 01/05 18:08
2F:→ VVll: 1f那样写 IDE会打枪XD 01/05 20:21
3F:推 GoalBased: 1f那个真的不行捏,我用vs2013 01/05 20:56
4F:→ andymai: @@? 打枪的理由是什麽? 误会什麽了??? 01/05 20:56
5F:→ GoalBased: 就编译不过阿 01/05 20:57
6F:→ andymai: 好奇了~我用VS2010可以~是在checkBox1的CheckedChanged事 01/05 20:57
7F:→ andymai: 件里写 timer1.Enabled = checkBox1.Checked 问题在哪? 01/05 20:57
8F:→ andymai: 不会是在 checkBox1.Checked 後面多打问号吧? 这就好笑罗 01/05 20:58
9F:推 GoalBased: 哈哈,原来是误会了,还以为那个 ? 是 ?:的 ? 01/05 21:00
10F:推 andymai: 还真的被我猜到了... 01/05 22:09
11F:→ AmosYang: XD 01/06 10:40
12F:→ AmosYang: 我的本意是「不需要判断式,直接执行『timer1.Enabled = 01/06 10:44
13F:→ AmosYang: checkBox1.Checked;』即可」;我原本的写法的确容易造 01/06 10:44
14F:→ AmosYang: 成误会 :D 01/06 10:45