Convert.ToBoolean fails with “0” value

后端 未结 8 2263
清歌不尽
清歌不尽 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:31

        public static bool GetBoolValue(string featureKeyValue)
        {
            if (!string.IsNullOrEmpty(featureKeyValue))
            {
                        try 
                        {
                            bool value;
                            if (bool.TryParse(featureKeyValue, out value))
                            {
                                return value;
                            }
                            else
                            {
                                return Convert.ToBoolean(Convert.ToInt32(featureKeyValue));
                            }
                        }
                        catch
                        {
                            return false;
                        }
             }
             else
             {
                      return false;
             }
       }
    

    You can call it like following -:

    GetBoolValue("TRUE") // true
    GetBoolValue("1") // true
    GetBoolValue("") // false
    GetBoolValue(null) // false
    GetBoolValue("randomString") // false
    

提交回复
热议问题