Convert.ToBoolean 的 c# 默认值

标签 c#

我有以下代码:

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/

相关文章:

c# - ScopeLock 模式 : Struct or Class?

c# - 使用官方 .NET SDK 在 Linux 上通过 cli 编译 C# 代码

c# - 改变winform中滚动条的大小

C# 开关类型

c# - 如何在 temp 以外的目录中创建临时文件?

c# - 如何在 C# 中获取表的 innerHTML

c# - 创建 ViewModel 后更新 ICommand

c# - 在 C# 中调试命令行参数

c# - 系统.安全.SecurityException : That assembly does not allow partially trusted callers

c# - 将值附加到列表