2014-08-29 47 views
0

如果我要寫這段代碼,它可以正常'if-else'佈局正常工作。三元與布爾條件在c#

if(isOn) 
{ 
    i = 10; 
} 
else 
{ 
    i = 20; 
} 

雖然我不能確定如何使用這個三元操作

 isOn = true ? i = 1 : i = 0; 

Error: Type of conditional expression cannot be determined because there is no implicitly conversion between 'void' and 'void'.

編輯轉換: 答案= i = isOn ? 10 : 20;

是否有可能與方法來做到這一點?

if(isOn) 
{ 
    foo(); 
} 
else 
{ 
    bar(); 
} 
+0

編輯補充方法的問題。 – 2014-08-29 16:17:53

+0

對於你的編輯:,你爲什麼要用方法做到這一點?你的「if」不夠清楚嗎?也取決於這些方法返回的內容。如果他們沒有返回任何「空白」,那麼我相信你不能使用三元操作符。 – Habib 2014-08-29 16:19:02

+3

如果您有新問題,請提出一個單獨的問題,請不要使用新問題更新現有問題。 – Habib 2014-08-29 16:20:35

回答

11

請嘗試以下操作。順便說一句,它只適用於值分配而不是方法調用。

i = isOn ? 10 : 20; 

參考:

+0

完美的謝謝。我編輯了這個問題,你知道這是否可以用方法嗎? – 2014-08-29 16:19:07

+0

@MarcC: - 你的方法返回什麼?由於答案取決於 – 2014-08-29 16:19:50

+0

這些方法是無效的。 – 2014-08-29 16:20:28

2

嘗試以下

i = isOn ? 10 :20 
-3

您需要:

i = true ? 10 : 20; 

其中true是您的情況。

+1

'isOn'是OP代碼 – Habib 2014-08-29 16:12:12

+0

中指定的'bool'(條件)OP已經公佈了這個答案。我= isOn? 10:20; – Donal 2014-08-29 16:30:11

+0

'true'部分僅僅是OP用條件替換它。 – user2711965 2014-09-03 14:56:29

5

你可能只是試試這個:

i = isOn? 10:20 

MSDN說:

The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.

編輯: -

如果你想調用的條件運算void方法,你可以使用委託,否則不可能爲方法使用三元運算符。

如果你的方法返回的東西,然後嘗試這樣的:

i = isOn ? foo() : bar(); //assuming both methods return int 
+1

@MarcC: - 檢查更新的答案! – 2014-08-29 16:24:19

3

你是在正確的軌道,但有點過上。 i = isOn ? 10 : 20;

這裏10會如果isOn == true被分配到i20將被分配到i如果isOn == false

2

嘗試以下操作:

i = isOn ? 10 : 20 
2

這裏有一個解釋,即可能的幫助。你要找的語句是:

i = isOn ? 10 : 20; 

這裏還有什麼意思:

(result) = (test) ? (value if test is true) : (value if test is false);