Convert.ToBoolean fails with “0” value

后端 未结 8 2230
清歌不尽
清歌不尽 2020-12-14 16:37

I\'m trying to convert the value \"0\" ( System.String ) to its Boolean representation, like:

var myValue = Convert.To         


        
8条回答
  •  独厮守ぢ
    2020-12-14 17:20

    If you know that it would be an int then you can convert it to int then to bool. Following will try for conversion to bool by attempting the string then attempting with number.

    public bool ToBoolean(string value)
    {
      var boolValue = false;
      if (bool.TryParse(value, out boolValue ))
      {
        return boolValue;
      }
    
      var number = 0;
      int.TryParse(value, out number))
      return Convert.ToBoolean(number);
    }
    

提交回复
热议问题