我有以下代码:
bool SilentUpdate { get; set;}
....
string temp = "";
SilentUpdate = Convert.ToBoolean(temp ?? "false");
我想在临时字符串为空时将SilentUpdate默认为false。上面的代码仍然发出错误“字符串未被识别为有效的布尔值”。
我该怎么做?
答案 0 :(得分:5)
这是一个稍微不同的逻辑,但这会给你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;
答案 1 :(得分:1)
您也可以使用Boolean.TryParse()
方法。它根据解析是否成功返回bool
。
bool flag;
if (Boolean.TryParse(temp, out flag))
答案 2 :(得分:1)
代码应为:
SilentUpdate = Convert.ToBoolean(string.IsNullOrEmpty(temp) ? "false" : temp)
您在代码中滥用了??
operator。它只返回第二个操作数,如果第一个操作数是null
,而不是假的。空字符串不是null
,因此temp ?? "false"
返回空字符串,这不是有效的布尔值。
答案 3 :(得分:1)
使用Convert.ToBoolean
要解析的字符串必须是Boolean.TrueString
,Boolean.FalseString
或null
。如果它有任何其他值,则会抛出异常,因此您必须确保在转换代码周围添加try...catch
,例如:
string temp = "nope";
SilentUpdate = Convert.ToBoolean(temp); // Exception: "String is not recognized as a valid Boolean"
使用Boolean.TryParse
您可以缓解此问题,并获得您想要的默认值:
string temp = "";
bool res = false;
SilentUpdate = (Boolean.TryParse(temp, out res) ? res : false);
Boolean.TryParse
如果解析成功则返回true
或false
,如果成功,则三元逻辑返回解析的内容,否则为假。
希望可以提供帮助。