我有以下代码:
bool SilentUpdate { get; set;}
....
string temp = "";
SilentUpdate = Convert.ToBoolean(temp ?? "false");
我想在临时字符串为空时将 SilentUpdate 默认设置为 false。上面的代码仍然发出错误“String was not recognized as a valid Boolean”。
我该怎么做?
最佳答案
这在逻辑上略有不同,但对于任何未正确转换为 bool 值的值,这都会为您提供 false
,这很可能是您真正想要的。
string temp = "";
bool result
if(!bool.TryParse(temp, out result))
{
result = false; //This line and the `if` is not actually necessary,
//result will be false if the parse fails.
}
SilentUpdate = result;
关于Convert.ToBoolean 的 c# 默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38153955/