Convert.ToBoolean fails with “0” value

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

    Here's a very forgiving parser that keys off of the first character:

    public static class StringHelpers
    {
        /// 
        /// Convert string to boolean, in a forgiving way.
        /// 
        /// String that should either be "True", "False", "Yes", "No", "T", "F", "Y", "N", "1", "0"
        /// If the trimmed string is any of the legal values that can be construed as "true", it returns true; False otherwise;
        public static bool ToBoolFuzzy(this string stringVal)
        {
            string normalizedString = (stringVal?.Trim() ?? "false").ToLowerInvariant();
            bool result = (normalizedString.StartsWith("y") 
                || normalizedString.StartsWith("t")
                || normalizedString.StartsWith("1"));
            return result;
        }
    }
    

提交回复
热议问题