作者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://www.ptt.cc/bbs/C_Sharp/M.1420451609.A.809.html
※ 編輯: VVll (211.72.185.162), 01/05/2015 18:04:48
→ AmosYang: 或著直接 timer1.Enabled = checkBox1.Checked ? :D 01/05 18:08
→ VVll: 1f那樣寫 IDE會打槍XD 01/05 20:21
推 GoalBased: 1f那個真的不行捏,我用vs2013 01/05 20:56
→ andymai: @@? 打槍的理由是什麼? 誤會什麼了??? 01/05 20:56
→ GoalBased: 就編譯不過阿 01/05 20:57
→ andymai: 好奇了~我用VS2010可以~是在checkBox1的CheckedChanged事 01/05 20:57
→ andymai: 件裡寫 timer1.Enabled = checkBox1.Checked 問題在哪? 01/05 20:57
→ andymai: 不會是在 checkBox1.Checked 後面多打問號吧? 這就好笑囉 01/05 20:58
推 GoalBased: 哈哈,原來是誤會了,還以為那個 ? 是 ?:的 ? 01/05 21:00
推 andymai: 還真的被我猜到了... 01/05 22:09
→ AmosYang: XD 01/06 10:40
→ AmosYang: 我的本意是「不需要判斷式,直接執行『timer1.Enabled = 01/06 10:44
→ AmosYang: checkBox1.Checked;』即可」;我原本的寫法的確容易造 01/06 10:44
→ AmosYang: 成誤會 :D 01/06 10:45