前言
JavaScript 的 Falsy Value
在 if ( Value ) 會自動轉換成 False
但在 C# 這邊的轉換就不一樣了
來看看 JS 和 C# 的差異也藉著差異來達到記憶點
🔖 文章索引
1. 空字串 to Boolean
2. 數字 to Boolean
3. 字串是數字 to Boolean
空字串 to Boolean
在 JavaScript 空字串會轉換成 false
在 C# 會跳出錯誤
// Cannot assign <null> to an implicitly-typed variable
// var test = null
// Correct usage
// string test = null;
var test = "";
if ( Convert.ToBoolean(test) )
{
Console.WriteLine('Y');
}
else
{
Console.WriteLine('N');
}
// output Error
// Unhandled exception. System.FormatException: String '' was not recognized as a valid Boolean.
只有 "true"
"false"
null
才能轉換成 boolean
數字 to Boolean
在 JavaScript Zero ( 0 )
會轉換成 false
其他都會轉換成 true
在 C# 也一樣只是需要用 Convert.ToBoolean()
var test = 0;
if ( Convert.ToBoolean(test) )
{
Console.WriteLine('Y');
}
else
{
Console.WriteLine('N');
}
// test = 0
// Output: N
// test = 1
// Output: Y
// test = -1
// Output: Y
字串是數字 to Boolean
在 JavaScript 除了空字串會是 false
其他都會是 true
在 C# 會需要先將字串轉成數字 Convert.ToInt32()
後在轉成 boolean
var test = "0";
if ( Convert.ToBoolean( Convert.ToInt32(test) ) )
{
Console.WriteLine('Y');
}
else
{
Console.WriteLine('N');
}
// test = "0"
// Output: N
// test = "1"
// Output: Y
// test = ""
// Unhandled exception. System.FormatException: The input string '' was not in a correct format.