Re: [問題] ?: 運算子的問題

作者: VVll (李奧納多皮卡丘)   2015-01-05 17:53:21
※ 引述《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;
作者: AmosYang (泛用人型編碼器)   2015-01-05 18:08:00
或著直接 timer1.Enabled = checkBox1.Checked ? :D
作者: VVll (李奧納多皮卡丘)   2015-01-05 20:21:00
1f那樣寫 IDE會打槍XD
作者: GoalBased (Artificail Intelligence)   2015-01-05 20:56:00
1f那個真的不行捏,我用vs2013
作者: andymai (人生只有一次)   2015-01-05 20:56:00
@@? 打槍的理由是什麼? 誤會什麼了???
作者: GoalBased (Artificail Intelligence)   2015-01-05 20:57:00
就編譯不過阿
作者: andymai (人生只有一次)   2015-01-05 20:57:00
好奇了~我用VS2010可以~是在checkBox1的CheckedChanged事件裡寫 timer1.Enabled = checkBox1.Checked 問題在哪?不會是在 checkBox1.Checked 後面多打問號吧? 這就好笑囉
作者: GoalBased (Artificail Intelligence)   2015-01-05 21:00:00
哈哈,原來是誤會了,還以為那個 ? 是 ?:的 ?
作者: andymai (人生只有一次)   2015-01-05 22:09:00
還真的被我猜到了...
作者: AmosYang (泛用人型編碼器)   2015-01-06 10:40:00
XD我的本意是「不需要判斷式,直接執行『timer1.Enabled =checkBox1.Checked;』即可」;我原本的寫法的確容易造成誤會 :D

Links booklink

Contact Us: admin [ a t ] ucptt.com