2013-02-27 108 views
2

輸入int值僅包含1或0。 我可以通過編寫if else語句來解決問題。將int轉換爲布爾值的更好方法

難道沒有辦法將int轉換爲boolean

感謝

+11

在問這個問題之前,你真的無法知道如何將一個int轉換爲bool嗎? – 2013-02-27 09:41:49

+4

男人,認真。 [是否很難找到](https://www.google.ru/search?q=msdn+convert+int+to+bool&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US :官方&客戶=火狐-A信道= fflb)? – icebat 2013-02-27 09:44:19

回答

21

我假設0表示假。這意味着真正不爲0,所以你可以這樣寫:

bool boolValue = intValue != 0; 
21
int i = 0; 
bool b = Convert.ToBoolean(i); 
+1

這是我可以在這裏看到的最佳解決方案。 – silverzx 2016-03-09 11:29:53

4

說笑歸說笑,如果你只希望你的輸入整數是0或1,你真的應該檢查這種情況。

int yourInteger = whatever; 
bool yourBool; 
switch (yourInteger) 
{ 
    case 0: yourBool = false; break; 
    case 1: yourBool = true; break; 
    default: 
     throw new InvalidOperationException("Integer value is not valid"); 
} 

開箱即用的Convert不會檢查這個;也不會yourInteger (==|!=) (0|1)

+1

有人不同意? – Rawling 2013-06-03 07:56:36