【问题标题】:string was not recognized as valid BOOL字符串未被识别为有效 BOOL
【发布时间】:2015-04-30 05:18:50
【问题描述】:
 oComm = CreateCommand("IsMapAccessExist", spParams, TypeOfConnectionString.GeoAppBuilder);

bool exists = true;    
    exists = Boolean.Parse(oComm.ExecuteScalar().ToString());

    return exist

exists 的值为 'true' 但它会引发错误

FormatException was caught
String was not recognized as a valid Boolean.

【问题讨论】:

  • 你确定吗? Boolean.Parse("true") 工作正常。你的字符串也有这些单引号?您是否调试了代码并检查了 ExecuteScalar 的确切返回值?
  • 它被预先设置为真,但是是的,Boolean.Parse(oComm.ExecuteScalar().ToString()) 标记了该错误....并且我用 SQL 在数据库中检查了记录存在
  • oComm.ExecuteScalar().ToString() 中返回了什么?当它试图将 oComm.ExecuteScalar().ToString() 中返回的内容转换为布尔值时,它会抛出异常。
  • 您的问题在于 oComm.ExecuteScalar().ToString(),它没有返回 'true' 或 'false',因此会引发 FormatException。
  • 730...不知道为什么 IsMapAccessExist 是一个返回记录的存储过程

标签: c# string parsing boolean


【解决方案1】:

虽然已经晚了,但这里是使用Boolean.TryParse的答案。

bool exists;    // No need to assign   
Boolean.TryParse(oComm.ExecuteScalar().ToString(),exists); // using TryParse

return exist; 

解释:(MSDN)

如果转换succeeded,如果值等于true,则包含true TrueStringfalse 如果值等于 FalseString。如果 转换failed,包含false

即使该值不是有效的TrueStringFalseString 字段,您也将始终获得所需的值。

目的是不惜一切代价避免异常。即使失败也会返回false,但程序会继续运行而不会停止。

TryParse 方法与 Parse 方法类似,只是 TryParse 方法在转换失败时不会抛出异常。

【讨论】:

    【解决方案2】:

    Boolean.Parse 必须传递“真”(Boolean.TrueString)或“假”(Boolean.FalseString)。

    你最好改用Boolean.TryParse,例如:

    string value = "true";
    bool couldParseString = Boolean.TryParse(value, out value);
    if ( couldParseString )
    {
        // do some stuff
    }
    else
    {
        // handle the string not being correct
    }
    

    注意:您通常应该以使用 {type} 为目标。尝试Parse 而不是 Parse。

    【讨论】:

      【解决方案3】:

      .ExecuteScalar() 返回第一行的第一列。要使其工作,请执行以下操作:

      int col = (int)oComm.ExecuteScalar();
      if(col == null)
          exists = false;
      else
          exists = true;
      

      【讨论】:

      • 如果 col != null 它仍然可以包含评估为 false 的值。
      • 假设您打算工作的意思是:false === 未选择行,true === 至少选择了一行;这可能是也可能不是预期的
      【解决方案4】:

      ExecuteScalar 不返回布尔值。阅读文档Here

      【讨论】:

      【解决方案5】:

      在我看来 ExecuteScalar 返回的东西不是 "True""False";也许"1""0"。调试方法如下:

      var tmp = oComm.ExecuteScalar().ToString();
      exists = Boolean.Parse(tmp);
      

      然后看看tmp 在调试器中持有什么

      【讨论】:

      • 如果在生产中发生这种情况,也要记录违规值
      猜你喜欢
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多